Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

regex - Insert code at the start and end of the outer nested code block only

I have some code like:

void main() {
//----------
  var a;
  var b;
  var c =[];
  var c = func(3);
  if (a == b) {
    print "nested";
  }    
//----------------
}

I want to select the inner portion in between brackets, This is what i have tried:

sed -re ':l;N;$!tl;N;s!(void w+() {)([^])*!1 Prepend; 2 append!g' test.txt

Edit:

I am trying to insert code after the first occurrence { and before the last occurrence of }.

Example:

void main() { 
test1
//-----------------
  var a;
  var b;
  var c =[];
  var c = func(3);
  if (a == b) {
    print "nested";
  }
test2
//-----------------
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...