Reputation: 1458
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:
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
Reputation: 88899
Try this with GNU sed:
sed "/function_1/{N;N;N;a new_text
}" filename
Upvotes: 7
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
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 printedc
to 4c
reaches 1 (so c
is true and !--c
is true), insert the lineYou 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
Reputation: 10039
sed '/function_1(/,/^[[:space:]]*}/ {
,/^[[:space:]]*}/ a\
Line that\
you want to\
insert (append) here
}' YourFile
}
(alone in the line with eventually some space before) from the section starting with function_1(
}
alone in your internal code like in your samplebe 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