I think awk is the best solution for what you really want to do:
$ awk '/{/{i++;if(i==1){print $0,"\ntest1";next}}{print}/}/{i--;if(i==1)print "test2"}' file void main() { test1
Explanation:
Here is a script in a multi-line form with some explanatory comments, if you prefer it in this form, save it in a file, say nestedcode , and run it as awk -f nestedcode code.c :
BEGIN{
source share