简体   繁体   English

找到匹配时使用sed替换行的开头

[英]Using sed to replace beginning of line when match found

I have a Java file. 我有一个Java文件。 I want to comment any line of code that contains the match: 我想评论包含匹配的任何代码行:

 myvar

I think sed should help me out here 我认为sed应该帮助我

 sed 's/myVar/not_sure_what_to_put_here/g' MyFile.java

I don't know what to put in: 我不知道该放什么:

not_sure_what_to_put_here

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出现的任何行的开头。

Any tips 有小费吗

Capture the whole line that contains myvar : 捕获包含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 option to save the changes in the file sed -i 's/\\(^.*myvar.*$\\)/\\/\\/\\1/' file . 使用-i选项将更改保存在文件sed -i 's/\\(^.*myvar.*$\\)/\\/\\/\\1/' file

Explanation: 说明:

(      # 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 

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 . 因此,这将查看整行,如果找到myvar则结果存储在第一个捕获组中,称为\\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 . 所以我们用整个行替换整行\\1前面有2个正斜杠//\\1当然forwardslashes需要转义为不要混淆sed所以\\/\\/\\1还注意括号需要转义除非你使用扩展sed正则表达式选项。

Try: 尝试:

sed -n '/myVar/{s|^|//|};p' MyFile.java

which means: when a line contains myVar , replace the beginning of the line with // . 这意味着:当一行包含myVar ,用//替换行的开头。

I was researching the same topic and found this solution which is simpler in terms of the regex 我正在研究相同的主题,并发现这个解决方案在正则表达式方面更简单

sed -e '/myvar/ s/^/\\/\\//' file

This adds // to column 0 of the line with the matching pattern. 这会将//添加到具有匹配模式的行的第0列。

However, I was looking for a solution which will allow me to add a character before the first character of the line (not on column 0). 但是,我正在寻找一种解决方案,它允许我在行的第一个字符之前添加一个字符(而不是在第0列)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM