-1

我有一些代码,例如:

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

我想选择括号之间的内部部分,这是我尝试过的:

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

编辑:

我试图在第一次出现之后{和最后一次出现之前插入代码}

例子:

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

4 回答 4

3

我认为awk对于您实际想要做的事情是一个更好的解决方案:

$ awk '/{/{i++;if(i==1){print $0,"\ntest1";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
//-----------------
}

解释:

这是带有一些解释性注释的多行形式的脚本,如果您更喜欢这种形式的脚本,请将其保存到文件nestedcode中,然后像这样运行它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,"\ntest1"
        #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"
}
于 2013-01-08T08:11:43.867 回答
2

这可能对您有用(GNU sed):

sed '/^void.*{$/!b;:a;/\n}$/bb;$!{N;ba};:b;s/\n/&test1&/;s/\(.*\n\)\(.*\n\)/\1test2\n\2/' file
  • /^void.*{$/!b如果该行不是void以 bail out 开头和结尾{(这可能需要根据您自己的需要进行定制)。
  • :a;/\n}$/bb;$!{N;ba}如果该行包含一个换行符,后跟一个}only,则分支到 labelb否则读取下一行并循环回 label a
  • :b在这里开始替换。
  • s/\n/&test1&/在第一个换行符之后插入第一个字符串。
  • s/\(.*\n\)\(.*\n\)/\1test2\n\2/在最后一个换行符的第二个之后插入第二个字符串。
于 2013-01-08T13:06:28.847 回答
-1

Try this regex:

{[^]*} // [^] = any character, including newlines.

JavaScript example of the Regex working:

var s = "void main() {\n//----------\nvar a;\nvar b;\nvar c =[];\nvar c = func(3);\n//----------------\n}"
console.log(s.match(/{[^]*}/g));
//"{↵//----------↵var a;↵var b;↵var c =[];↵var c = func(3);↵//----------------↵}"

(I know this ain't JS question, but it works to illustrate that the regex returns the desired result.)

于 2013-01-08T07:59:56.960 回答
-1

sed,默认情况下,在单行上运行。它可以通过使用N命令将多行读入模式空间来对多行进行操作。

例如,以下 sed 表达式将连接文件中的连续行,@它们之间带有符号:

sed -e '{
N
s/\n/ @ /
}'

(示例来自http://www.thegeekstuff.com/2009/11/unix-sed-tutorial-multi-line-file-operation-with-6-practical-examples/

于 2013-01-08T08:00:20.470 回答