Notifications
Clear all

SED: Insert a new line after first match

1 Posts
1 Users
0 Likes
6 Views
Tharindu
(@tharindu)
Reputable Member Admin
Joined: 10 years ago
Posts: 307
Topic starter  

So, I was in a situation where I need to add a new line of code to a configuration file programmatically. The new line must be added after the first occurrence of the keyword. The file had multiple occurrences of the keyword. I couldn't perform a simple append with Sed because it would add a new line after each occurrence of the keyword. Doing so would break my script. Let's see how I did it.

Let's say I have a file named input.txt with following content,

Line one
Line two
Line three
Special line
Line five
Line six
Special line
Line eight
Line nine
Special line

As you can see, there are multiple occurrences of Special line. What I need to do is to add a new line after the first occurrence of the Special line with content New inserted line. The Sed command to achieve this as follows.

sed -i $'/Special line/{iNew inserted line\n:a;n;ba}' input.txt

 Happy coding!

This topic was modified 2 years ago 2 times by Tharindu

   
Quote
Topic Tags
Share:
Back to top button