Notifications
Clear all
Topic starter 24/09/2022 6:17 am
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