将code。在外部嵌套code块的开始和结束只 [英] Insert code at the start and end of the outer nested code block only
问题描述
我有一些code,如:
无效的主要(){
// ----------
风险价值;
变种B:
变种C = [];
变种C = FUNC(3);
如果(A == B){
打印嵌套;
}
// ----------------
}
我要选择在括号内部分,这是我曾尝试:
SED -re':!!!L,N; $ TL; N; S(无效\\ w + \\(\\)\\ {)([^])* \\ 1 prePEND ;!\\ n \\ 2 \\ nappend G'的test.txt
编辑:
我想第一次出现后插入code {
键,最后一次出现在}
例如:
无效的主要(){
TEST1
// -----------------
风险价值;
变种B:
变种C = [];
变种C = FUNC(3);
如果(A == B){
打印嵌套;
}
TEST2
// -----------------
}
我觉得 AWK
是你的更好的解决方案实际上的希望这样做:
$ awk的'/ {/ {我++;如果(我== 1){$打印0,\\ ntest1;接下来}} {}打印/} / {我 - ;如果(我== 1)打印测试2}'文件
无效的主要(){
TEST1
// -----------------
风险价值;
变种B:
变种C = [];
变种C = FUNC(3);
如果(A == B){
打印嵌套;
}
TEST2
// -----------------
}
说明:
下面是多行的形式,脚本使用一些解释性的意见,如果你preFER它以这种形式将它保存到一个文件中说嵌套code
和运行它像的awk -f嵌套code codeC
:
BEGIN {
#Track嵌套层次
按nestLevel = 0
}
/ {/ {
#系统线路包含在{等方面加大按nestLevel
按nestLevel ++
#Only增加code。如果按nestLevel为1
如果(按nestLevel == 1){
#PRINT以下行的匹配线和新的code
打印$ 0,\\ ntest1
#Skip到下一行,以便下一个块
#不打印当前行两次
下一个
}
}
{
#PRINT所有行
打印
}
/} / {
#线包含在}因此降低按nestLevel
nestlevel--
#Only打印code。如果nestleve为1
如果(按nestLevel == 1)
打印TEST2
}
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;\n\2\nappend!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
//-----------------
}
I think awk
is a better solution for what you actually want to do:
$ 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
//-----------------
}
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,"\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"
}
这篇关于将code。在外部嵌套code块的开始和结束只的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!