regex - 仅在外部嵌套代码块的开头和结尾插入代码

标签 regex linux sed awk

我有一些代码,例如:

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 前置;\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
//-----------------
}

最佳答案

我认为 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"
}

关于regex - 仅在外部嵌套代码块的开头和结尾插入代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14210497/

相关文章:

c - 有没有办法在运行时确定可用的堆栈空间?

bash - 使用 Shell 命令对文件进行排序

regex - 使用 sed 时的多个条件

java - JXDatePicker 使用 SimpleDateFormat 将 dd.MM.yy 格式化为当前世纪的 dd.MM.yyyy

c++ - 不同进程之间交换和存储值

linux - 使用 grep 命令 Linux 查找文件的行号

bash - 如何在模式 "Using SED"之前插入字符串或换行符(不替换模式)在 MAC OS

java - 如何将此 glob 转换为具有附加约束的正则表达式(使用 Java 7)?

javascript - jquery RegExp 没有按我的预期工作

regex - 在匹配中使用时如何使子规则/正则表达式不区分大小写?