How to add a string under a specific line in a shell?

In Shell scripts, you can use the sed command to add a string below a specified line.

Assuming you have a file named file.txt with the following content:

Line 1
Line 2
Line 3
Line 4
Line 5

To add a new string below line 3, you can use the following command:

sed '3a\New line' file.txt

After running this command, the content of file.txt will be changed to:

Line 1
Line 2
Line 3
New line
Line 4
Line 5

In the above command, 3a indicates to add text after line 3, with \ used to escape newline characters, and “New line” being the string content to add.

If you want to modify the file directly instead of outputting to the terminal, you can use the -i option.

sed -i '3a\New line' file.txt

At this moment, the content of file.txt will be directly altered.

bannerAds