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
- sed: is the command itself
- 3: is the line where you want the new line inserted
- i: is the parameter that says sed to insert the line.
- line 3: is the text to be added in that position.
- filename: is the file where sed is going to act.
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.
No comments:
Post a Comment