I think awk
is a better solution for what you actually want to do:
$ awk '/{/{i++;if(i==1){print $0,"
test1";next}}{print}/}/{i--;if(i==1)print "test2"}' file
void main() {
test1
//-----------------
var a;
var b;
var c =[];
var c = func(3);
if (a == b) {
print "nested";
}
test2
//-----------------
}
Explanation:
Here is the script in multiline form with some explanatory comments, if you prefer it in this form save it to a file say nestedcode
and run it like awk -f nestedcode code.c
:
BEGIN{
#Track the nesting level
nestlevel=0
}
/{/ {
#The line contained a { so increase nestlevel
nestlevel++
#Only add code if the nestlevel is 1
if(nestlevel==1){
#Print the matching line and new code on the following line
print $0,"
test1"
#Skip to next line so the next block
#doesn't print current line twice
next
}
}
{
#Print all lines
print
}
/}/ {
# The line contained a } so decrease the nestlevel
nestlevel--
#Only print the code if the nestleve is 1
if(nestlevel==1)
print"test2"
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…