Skip to content
Advertisement

sed – insert line after X lines after match

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.

Advertisement

Answer

Try this with GNU sed:

sed "/function_1/{N;N;N;a new_text
}" filename
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement