我有一个Java文件.我想评论包含匹配的任何代码行:
myvar
Run Code Online (Sandbox Code Playgroud)
我认为sed应该帮助我
sed 's/myVar/not_sure_what_to_put_here/g' MyFile.java
Run Code Online (Sandbox Code Playgroud)
我不知道该放什么:
not_sure_what_to_put_here
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我不想替换myVar,但我想插入
//
Run Code Online (Sandbox Code Playgroud)
到myVar出现的任何行的开头.
有小费吗
Chr*_*our 40
捕获包含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
}
}
Run Code Online (Sandbox Code Playgroud)
使用该-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
Run Code Online (Sandbox Code Playgroud)
因此,这将查看整行,如果myvar找到存储在第一个捕获组中的结果,则引用a \1.所以我们用整个行替换整行\1,前面有2个正斜杠//\1,当然forwardslashes需要转义为不要混淆sed所以\/\/\1请注意括号需要转义,除非你使用扩展的正则表达式选项sed.
尝试:
sed -n '/myVar/{s|^|//|};p' MyFile.java
Run Code Online (Sandbox Code Playgroud)
这意味着:当一行包含 时myVar,将该行的开头替换为//。