Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed - insert line after X lines after match

Tags:

linux

shell

sed

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:

  1. find text "function_1"
  2. skip 3 lines
  3. insert new line

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.

like image 910
Nuclear Avatar asked May 07 '15 11:05

Nuclear


People also ask

How do you add a new line in sed?

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“.

How do I add a line to a certain line number?

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.


1 Answers

Try this with GNU sed:

sed "/function_1/{N;N;N;a new_text
}" filename
like image 194
Cyrus Avatar answered Oct 22 '22 12:10

Cyrus