找到匹配项时使用 sed 替换行首 [英] Using sed to replace beginning of line when match found
问题描述
我有一个 Java 文件.我想注释包含匹配项的任何代码行:
I have a Java file. I want to comment any line of code that contains the match:
myvar
我认为 sed 应该可以帮助我
I think sed should help me out here
sed 's/myVar/not_sure_what_to_put_here/g' MyFile.java
我不知道该放什么:
not_sure_what_to_put_here
在这种情况下,我不想替换 myVar 但我想插入
as in this case, I don't want to replace myVar but the I want to insert
//
到 myVar 出现的任何行的开头.
to the beginning of any line myVar occurs on.
任何提示
推荐答案
捕获包含 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
}
}
使用 -i
选项将更改保存在文件 sed -i 's/\(^.*myvar.*$\)/\/\/\1/'文件
.
Use the -i
option to save the changes in the file 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
所以 \/\/\1
还要注意括号需要转义,除非你使用 sed
的扩展正则表达式选项.
So this looks at the whole line and if myvar
is found the results in stored in the first capture group, referred to a \1
. So we replace the whole line \1
with the whole line preceded by 2 forward slashes //\1
of course the forwardslashes need escaping as not to confused sed
so \/\/\1
also note that brackets need escaping unless you use the extended regex option of sed
.
这篇关于找到匹配项时使用 sed 替换行首的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!