Sed - insert a line after X lines after the match

I have the following content:

void function_1() { //something (taking only 1 line) } ->INSERT LINE HERE<- //more code 

Using sed, I want to insert a line on the INSERT LINE HERE shortcut. The easiest way:

  • find the text "function_1"
  • skip 3 lines
  • add new line

But none of the known sed options does this work.

 sed '/function_1/,3a new_text 

inserts new_text immediately 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 in several non-template locations

Thanks.

+6
source share
4 answers

Try the following:

 sed "/function_1/{N;N;N;a new_text }" filename 
+4
source
 sed '/function_1(/,/^[[:space:]]*}/ { ,/^[[:space:]]*}/ a\ Line that\ you want to\ insert (append) here }' YourFile 
  • insert the line after } (alone in the line ending with some space before) from the section starting with function_1(
  • I assume that in the internal code does not exist } , as in your example

to be sure of the choice based on the name of the function, because it can be used (and normalized) as a call to the function itself in another section of the code, so it is better /^void function_1()$/

+2
source

Use awk:

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

You can simply use !--c , but adding that the check for c is true and also means that c does not continue to decrease beyond 0.

+1
source

Do not count, match:

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

Here, the block between the declaration and the closing bracket is examined, and then TEXT_TO_INSERT is added after closing.

0
source

Source: https://habr.com/ru/post/986734/


All Articles