Tuesday, June 12, 2007

Add/Change/Insert lines to a file using sed


Using sed we can Add/Change/Insert lines in a file, I found it very useful, hope you too !

$ cat namedb.txt
Nina:London
Apen:India
Lokesh:India

#Add a line
a)
$ sed '
/Apen/ a\
Add this line after Apen
' namedb.txt

Output
Nina:London
Apen:India
Add this line after Apen
Lokesh:India

b)
$ sed '
2 a\
Add this line after 2nd line
' namedb.txt

Output
Nina:London
Apen:India
Add this line after 2nd line
Lokesh:India

#Insert a new line before
c)
$ sed '
/Apen/ i\
Insert this line after Apen
' namedb.txt

Output
Nina:London
Insert this line after Apen
Apen:India
Lokesh:India

Similarly one can mention the line number (case b above)

#Change a line
d)
$ sed '
/Apen/ c\
Change the line with Apen to this line
' namedb.txt

output
Nina:London
Change the line with Apen to this line
Lokesh:India

Similarly one can mention the line number to change (case b above)

4 comments:

Unknown said...

I've always been interested in sed/awk. I usually reach for Perl or Python or something first to run regexes and screw with text, when I know there are command line tools there to do what I want to do.

So thanks for posting these tips.

Unknown said...

@Ken, Thanks.

abonfietti said...

Looks great, thanks !

What if I have to add the same string "add this line" to many files at once ?

Unknown said...

@abonfietti, sorry for a late reply.

e.g. take the example # a) above:

sed '
/Apen/ a\
Add this line after Apen
' namedb.txt


On multiple files:

e.g. Lets perform this on all .txt files present in this directory as well as all sub-dirs:

_______
for file in $(find . -name "*.txt")
do
echo "Adding the line on file:$file"

sed '
/Apen/ a\
Add this line after Apen
' $file > $file.tmp


mv $file.tmp $file

done
_______


To perfomr this on all .txt files under this directory.

______
ls *.txt | while read file
do
....
....
done
______

The same can be written as:

for file in $(ls *.txt)
...
...

Hope this helps.

Regards,
Jadu

© Jadu Saikia www.UNIXCL.com