Insert lines in files with sed
Written by Guillermo Garron
Date: 2014-11-29 21:05:20 00:00
How to insert lines into text files using stream editor (sed)
Q. How can I insert a line in a specific position in a text file?
A. You can use
sed in order to add or insert a line in a specific position of a text file.
Let's say you have a file named, well file.txt and you want to insert a line in position 2, with this string Hello World.
The command should be:
sed '2i\'$'\n''Hello World'$'\n' file.txt
Now, as a bonus, let's see how to do it in a bunch of files.
for i in *.txt; do sed '2i\'$'\n''Hello World'$'\n' $i > tmp/$i ; done