我有一个 Java 文件。我想注释包含匹配的任何代码行:
myvar
我认为 sed 应该在这里帮助我
sed 's/myVar/not_sure_what_to_put_here/g' MyFile.java
我不知道要输入什么:
not_sure_what_to_put_here
在这种情况下,我不想替换 myVar 但我想插入
//
到 myVar 出现的任何行的开头。
Any tips
捕获包含的整行myvar
:
$ sed 's/\(^.*myvar.*$\)/\/\/\1/' file
$ cat hw.java
class hw {
public static void main(String[] args) {
System.out.println("Hello World!");
myvar=1
}
}
$ sed 's/\(^.*myvar.*$\)/\/\/\1/' hw.java
class hw {
public static void main(String[] args) {
System.out.println("Hello World!");
// myvar=1
}
}
Use the -i
保存文件更改的选项sed -i 's/\(^.*myvar.*$\)/\/\/\1/' file
.
解释:
( # Start a capture group
^ # Matches the start of the line
.* # Matches anything
myvar # Matches the literal word
.* # Matches anything
$ # Matches the end of the line
) # End capture group
所以这会查看整条线,如果myvar
发现结果存储在第一个捕获组中,称为\1
。所以我们更换整条线\1
整行前面有 2 个正斜杠//\1
当然,正斜杠需要转义以免混淆sed
so \/\/\1
另请注意,除非您使用扩展的正则表达式选项,否则括号需要转义sed
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)