Nuclear
Nuclear

Reputation: 1458

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.

Upvotes: 16

Views: 11676

Answers (4)

Cyrus
Cyrus

Reputation: 88899

Try this with GNU sed:

sed "/function_1/{N;N;N;a new_text
}" filename

Upvotes: 7

William Pursell
William Pursell

Reputation: 212584

Don't count, match:

sed -e '/^void function_1()/,/^}$/ { /^}$/a\
TEXT TO INSERT
}' input

This looks at the block between the declaration and the closing brace, and then append TEXT_TO_INSERT after the closing brace.

Upvotes: 1

Tom Fenech
Tom Fenech

Reputation: 74695

Use awk:

awk '1;/function_1/{c=4}c&&!--c{print "new text"}' file
  • 1 is a shorthand for {print}, so all lines in the file are printed
  • when the pattern is matched, set c to 4
  • when c reaches 1 (so c is true and !--c is true), insert the line

You could just use !--c but adding the check for c being true as well means that c doesn't keep decreasing beyond 0.

Upvotes: 4

NeronLeVelu
NeronLeVelu

Reputation: 10039

sed '/function_1(/,/^[[:space:]]*}/ {
 ,/^[[:space:]]*}/ a\
Line that\
you want to\
insert (append) here
   }' YourFile
  • insert the line after the } (alone in the line with eventually some space before) from the section starting with function_1(
  • i assume there is no } alone in your internal code like in your sample

be carreful on selection based on function name because it could be used (and normaly it is) as a call to the function itself in other code section so maybe a /^void function_1()$/ is better

Upvotes: 2

Related Questions