Hi Guys,
If you want to add a line in file at specific line number through script. Below examples will help you to do it.
For example you have a file named file1.txt, file content are as below.
[email protected]:~ # cat file1.txt tecadmin 1 tecadmin 2 tecadmin 4
Now you required to add text “tecadmin 3” at line number 3, use below command
[email protected]:~ # sed '3itecadmin 3' file1.txt > file1.txt.tmp
Above command will create a new file file1.txt.tmp with expected output
[email protected]:~ # cat file1.txt.tmp tecadmin 1 tecadmin 2 tecadmin 3 tecadmin 4
Replace origin file with tmp file
[email protected]:~ # cp file1.txt.tmp file1.txt
Details of the `sed` command:
sed: is the command itself.
2: line number where new line will be inserted.
i: parameter, which told sed to insert line.
tecadmin 2: text to be added.
file1.txt: is the file in which new line need to add.
file1.txt.tmp: New file with updated content.
You also can use -i modifier to edit the file itself without creating an intermediate file
$ sed -i ‘3itecadmin 3’ file1.txt
Moreover, if you are not sure about the changes that will be made, add a suffix to the -i flag that will make a backup of the original file
$ sed -i.bak ‘3itecadmin 3’ file1.txt