我正在研究 MAC OSX。我正在编写 shell 脚本来为文件中的所有日志消息添加前缀“//”。我写了以下 sed 脚本:
sed -i '' "s|"log+*"|"//log"|g" filename
Run Code Online (Sandbox Code Playgroud)
当日志消息只有一行时,脚本工作正常。但是如果日志有多行,它就会失败。例如:
log("hi
how are
you");
Run Code Online (Sandbox Code Playgroud)
输出结果是:
//log("hi
how are
you");
Run Code Online (Sandbox Code Playgroud)
但是,我希望输出是:
//log("hi
// how are
// you");
Run Code Online (Sandbox Code Playgroud)
由于我没有经常使用 sed,我不知道该怎么做。那么,是否可以使用 sed 来做到这一点。如果是如何?
谢谢
最简单的方法是使用地址范围
sed "/^\s*log.*;$/ s|^|//|; /^\s*log/, /);$/ s|^|//|" input
Run Code Online (Sandbox Code Playgroud)
它能做什么?
/^\s*log.*;$/ s|^|//|如果该行以开头log和结尾,;则替换开头,^用//
/\s*^log/, /);$/ s|^|//|"
/^log/, /);$/这是一个地址范围。对于此范围内的所有行,执行替换。行的范围从第一个正则表达式匹配到结束匹配。测试
$ cat input
log("hi
how are
you");
this will also be not commented;
log ("test);
this is not commented;
$ sed "/^\s*log.*;$/ s|^|//|; /^\s*log/, /);$/ s|^|//|" input
//log("hi
// how are
// you");
this will also be not commented;
//log ("test);
this is not commented;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2572 次 |
| 最近记录: |