利用sed 's/^\( *\)\/\/\(.*myVar.*$\)/\1\2/' file
$ cat hw.java
class hw {
public static void main(String[] args) {
System.out.println("Hello World!");
// myVar=1
//myVar.setAge(200);
//myVar.setPlanet("mars");
}
}
$ sed 's/^\( *\)\/\/\(.*myVar.*$\)/\1\2/' hw.java
class hw {
public static void main(String[] args) {
System.out.println("Hello World!");
myVar=1
myVar.setAge(200);
myVar.setPlanet("mars");
}
}
使用-i选项保存文件中的更改sed -i 's/^\( *\)\/\/\(.*myVar.*$\)/\1/' file:
解释:
^ # Matches the start of the line
\( # Start first capture group
* # Matches zero or more spaces
\) # End first capture group
\/\/ # Matches two forward slashes (escaped)
\( # Start second capture group
.* # Matches anything
myVar # Matches the literal word
.* # Matches anything
$ # Matches the end of the line
\) # End second capture group
在这里,我们将空格捕获到//,然后在 if 之后myVar的所有内容并替换为\1\2。
您的逻辑几乎就在那里,但是有几件事,首先是转义了所有括号,其次您^( *)\/\/不希望^\\在行首捕获两个转义的正斜杠,其中的空格不是两个反斜杠:
如果您不想转义括号,则需要使用扩展的正则表达式标志,sed它的-rfor GNU sedonOSX它是-E这样检查的sed --help。
sed -r 's/^( *)\/\/(.*myVar.*$)/\1\2/' file
注意:当您匹配整行(从^到$)时,该g标志是多余的。