sed - insert line after X lines after match
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 withfunction_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
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.
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 (soc
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.
Try this with GNU sed:
sed "/function_1/{N;N;N;a new_text
}" filename