Get updates via: rss | twitter | email | google+

Add a line to a specific position in a file using Linux sed

Written by Guillermo Garron .
Date: 2011-07-30 13:50:09 -0400

Add a line in a specific position with Linux

If you need to add a line to a file in Linux, and you need to add that line in a specific position of the file there is an easy solution, even if you need to do it to hundreds of thousands of files.

Consider this file:

line 1
line 2
line 4

As you can see we missed line 3, so to add it just execute this command:

sed '3iline 3' filename.txt

Parts of the command

That will just put the result in the screen but the file will remain the same, you can redirect the output to a new file:

sed '3iline 3' input.txt > output.txt

Shell script add a line to multiple files

Now, if you need to do this with hundreds of files:

for i in *; do sed '3iline 3"' $i > /tmp/$i ; done

You can then copy from /tmp/ to your actual folder and you have been changed all files in current folder.


permalink

If you enjoyed the article, please share it

twitter | facebook | google+ | linkedin | email | reddit


You may want to subscribe to my newsletter

If you want to receive articles similar to this every month sign in to our Newsletter and joing other 2.000 readers

You can see an example of what is going to be sent to you here

powered by TinyLetter