16

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.

Nuclear
  • 1,316
  • 1
  • 11
  • 17

4 Answers4

7

Try this with GNU sed:

sed "/function_1/{N;N;N;a new_text
}" filename
Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • 3
    Alternatively: `sed '/function_1/!{p;d;};n;n;n;a new text'` It's more roundabout but works without a newline in the sed code (because the `a` command is at the end). – Wintermute May 07 '15 at 12:28
  • I guess that this approach doesn't work on all versions of sed, as POSIX specifies that you should use `a\ ` followed by a newline in order to append text. – Tom Fenech May 07 '15 at 13:05
  • @TomFenech: I added "GNU sed". Thank you. – Cyrus Nov 03 '20 at 11:36
  • I like this solution but i want some `tab` in my `next text` – Satish May 09 '22 at 16:07
4

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.

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
2
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

NeronLeVelu
  • 9,908
  • 1
  • 23
  • 43
1

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.

William Pursell
  • 204,365
  • 48
  • 270
  • 300