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
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.
If you enjoyed the article, please share it
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