我有一些代码,例如:
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/