I have the following contents:
void function_1()
{
//something (taking only 1 line)
}
->INSERT LINE HERE<-
//more code
Using sed, I want to insert line at the INSERT LINE HERE label. The easiest way should be:
But none of the known sed options do the job.
sed '/function_1/,3a new_text
inserts new_text right after 'function_1'
sed '/function_1/,+3a new_text
inserts new_text after each of the next 3 lines, following 'function_1'
sed '/function_1/N;N;N; a new_text
inserts new_text at multiple places, not related to the pattern
Thanks.
There are different ways to insert a new line in a file using sed, such as using the “a” command, the “i” command, or the substitution command, “s“.
In the first line, we added the line number for insertion. Secondly, we specified the insert action in the same line. Then, in the next line, we added the phrase we wanted to insert. In the end, we need to put a dot (.) to end the input mode and then add xit to save the changes and quit the editor.
Try this with GNU sed:
sed "/function_1/{N;N;N;a new_text
}" filename
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With