Bash 使用sed或awk注释掉文件中的块
我想用sed或awk注释掉文件中的一段代码 例输入Bash 使用sed或awk注释掉文件中的块,bash,awk,sed,Bash,Awk,Sed,我想用sed或awk注释掉文件中的一段代码 例输入 this is source file; line one code; line two code; line three code; line four code; line 5 code; if something then line 6 code; end if; 在本文中,我想从代码的第二行注释掉if 即输出应为 this is source file; line one code; /* line two code; line
this is source file;
line one code;
line two code;
line three code;
line four code;
line 5 code;
if something then
line 6 code;
end if;
在本文中,我想从代码的第二行注释掉if
即输出应为
this is source file;
line one code;
/*
line two code;
line three code;
line four code;
line 5 code;
if something then
line 6 code;
end if;
*/
试过了,这个
awk '"/line two code;/{e=0}/end if;/" {printf("%s%s%s\n", "/*", $0, "*/"); next} {print}'
但是,它在每行代码之间附加了/*和*/
我想从第二行代码
注释到结束,如果
:
您可以像这样使用awk
:
awk '/line two code;/{print "/*"; p++} 1; p && /end if;/{print "*/"; p=0}' file
this is source file;
line one code;
/*
line two code;
line three code;
line four code;
line 5 code;
if something then
line 6 code;
end if;
*/
使用
sed
的解决方案的工作方式大致相同:
sed '/line two code;/s|$|\n/*|; /end if;/s|$|\n*/|' file
Arunkumar Ramamoorthy,我认为以下代码可能会有所帮助:
awk '/line two code;/{print "/*"}{print $0}/end if;/{print "*/"}' input
至少,它可以在我的mac电脑上运行
➜ ShellBean cat input
this is source file;
line one code;
line two code;
line three code;
line four code;
line 5 code;
if something then
line 6 code;
end if;
➜ ShellBean awk '/line two code;/{print "/*"}{print $0}/end if;/{print "*/"}' input
this is source file;
line one code;
/*
line two code;
line three code;
line four code;
line 5 code;
if something then
line 6 code;
end if;
*/
这可能适用于您(GNU-sed):
这会将两个文本之间的行填充到模式空间中,然后在打印时插入并追加所需的行
注意,$”…
是一种bashism,允许一行代码包含换行符,但是如果您愿意,多个命令也可以:
sed -e '/line two code/{:a;N;/end if/!ba;i/*' -e 'a*/' -e '}' file
学习分步调试
awk
代码。我不认为,“/line two code;/{e=0}/end if;/”
正在做您认为/需要的事情。下面是一个很好的解决方案。祝大家好运。获得阿诺德·罗宾斯的《有效的Awk编程》第四版,阅读前几页,然后重新审视你的代码。太棒了。适用于给定的用例。但是,如果我有两个if语句,那么它也会为第二个end if添加end comment(*/),对于给定的场景效果很好。但对于ex:它不适用于此源,这是源文件;第一行代码;第二行代码;第三行代码;第四行代码;第5行代码;如果有的话,那么第6行代码;如果结束;如果是其他东西,则第7行代码;如果结束;好的,试试这个awk
命令:awk'/第二行代码/{print”/*;p++}1;p&;结束(若有)/{print“*/”p=0}文件
Perfect:)。工作起来很有魅力。谢谢你@anubhava
sed -e '/line two code/{:a;N;/end if/!ba;i/*' -e 'a*/' -e '}' file