Insert lines on top of a text file

I have a bash script that runs Oracle RMAN backups and logs every steps that it does to a logfile. At the end of the backup run the script automatically sends an email to me containing the entire log. The log file gets very detailed chatter of the backup run making the file very long.  Exit codes and disk statistics logically can be seen towards the end of the file (because exit code is only available after the script completes).  I don’t want to scroll all the way down this file just to see what i wanted to see “did the backup completed OK? exitcode = 0”.<br />
Here is the snippet of the codes i added to implement this trick into the backup scripts:

..
..
sendmail() {
returncode=$?

#insert the return code on top of the $LOGFILE
sed -i ‘1i Return Code: $returncode’ >> $LOGFILE

echo “”
echo “—————————————————-” >> $LOGFILE
df >> $LOGFILE
echo “” >> $LOGFILE
echo “—————————————————-” >> $LOGFILE
echo ” Backup Ended :   ” date >> $LOGFILE
..
..
..

Various solutions i found on the net are the following:

Unix ‘Sed’ utility is suitable for adding/appending, changing or inserting lines to files.

The bash script using ‘sed’:

#!/bin/sh
FILES=$(echo *.in)
for file in $FILES
do
echo “Modifying file : $file”

sed ‘1i\
h1|t|4′ $file | sed ‘2i\
h2|r|0′ | sed ‘$a\
#End’ > $file.tmp

mv $file.tmp $file
done

</pre>
With newer version of 'sed', the use of temporary files in the above bash  script can be avoided by using '-i' option. 
<blockquote><font face="Courier New">-i[SUFFIX], --in-place[=SUFFIX]
edit files in place (makes backup if extension supplied)
</font></blockquote><pre>

A plain bash script without using ‘sed’ utility would be something like this:

for file in $(ls *.in)
do
echo “Modifying file : $file”
echo “h1|t|4” >> $file.tmp
echo “h2|r|0” >> $file.tmp
cat $file >> $file.tmp
echo “#End” >> $file.tmp
mv $file.tmp $file
done

Awk way of inserting a line of text in any line number (say insert text ‘first line’ as line number 1 of file.txt)

$ awk ‘NR==1{print “first line”}1’ file.txt

Sed way:<br />

sed -i ’1i Prepended line’ /tmp/newfile


References:
http://unstableme.blogspot.com/2010/06/insert-text-at-top-of-file-in-unix.html
http://unstableme.blogspot.com/2010/01/sed-save-changes-to-same-file.html

Advertisements

About this entry