Operating System - HP-UX
1834449 Members
1855 Online
110067 Solutions
New Discussion

Re: Script to insert a line into a text file

 
SOLVED
Go to solution
Preet Dhillon
Advisor

Script to insert a line into a text file

Hi Peeps,

I need a script which will read the first line in every file in a directory and depending on the result, insert a line of text at the start of the file and save it.
Is there a way of doing this using a script instead of having to do it manually using vi?

Many thanks in advance.

Preet :-)
Nothing succeeds like excess
3 REPLIES 3
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: Script to insert a line into a text file

Sure no problem; something like this:

TDIR=${TMPDIR:-/var/tmp}
PID=${$}

T1=${TDIR}/X${PID}_1.txt

ls | while read X
do
if [ -f "${X}" -a -w "${X}" -a -r "${X}" ]
then
L1=`line < ${X}`
if [ "${L1}" = "test string" ]
then
echo "Insert this stuff" > $T1
cat ${X} >> $T1
mv $T1 $X
fi
fi
done

You might want to replace the = comparison with a grep -q and test the result.

You could also do it with sed.

Regards, Clay
If it ain't broke, I can fix that.
Rodney Hills
Honored Contributor

Re: Script to insert a line into a text file

How about the following one liner...

perl -p -i -e 'if ($. == 1 and /pattern/) { print "new line at start of file"}' *

where pattern is a regexp to search for (use ! /pattern/ for negative sense).

The * on the end will apply to all files in current directory. If you wish to save the original file change -i option to -i.old and this will save the original files with a .old extension.
There be dragons...
Vincenzo Restuccia
Honored Contributor

Re: Script to insert a line into a text file

cat file|while read i
do
echo $i >> file_new
echo >> file_new
done