Perl vs Sed regex substitue /(foo | bar)/

时间:2015-11-04 16:15:41

标签: regex perl sed

我希望有人可以解释为什么sed在perl为此问题所做的工作时不起作用:

$ egrep "(foo|bar)=0" /var/tmp/test.txt
This is example output of the test.txt file foo=0
This is another example output of the bar=0 test.txt file
$ sed -ir 's/(foo|bar)=0//g' /var/tmp/test.txt
$ egrep "(foo|bar)=0" /var/tmp/test.txt
This is example output of the test.txt file foo=0
This is another example output of the bar=0 test.txt file
$

尝试用perl代替作品:

$ egrep "(foo|bar)=0" /var/tmp/test.txt
This is example output of the test.txt file foo=0
This is another example output of the bar=0 test.txt file
$ perl -ne 's/(foo|bar)=0//g;print;' -i /var/tmp/test.txt
$ egrep "(foo|bar)=0" /var/tmp/test.txt
$ 

有没有办法让sed完成perl在这里做的事情?谢谢你!

1 个答案:

答案 0 :(得分:6)

这只是您提供给sed的参数顺序的问题。说sed -r -i,你会发现它有效。

当您说sed -ir时,您正在设置就地编辑但不是-r模式。为什么?由于-r被理解为-i的参数,因此您最终会获得file + r备份。

完整测试:

$ sed -ir 's/(foo|bar)=0//g' file

filefiler相等!

$ cat file
This is example output of the test.txt file foo=0
This is filenother example output of the bar=0 test.txt file
$ cat filer
This is example output of the test.txt file foo=0
This is filenother example output of the bar=0 test.txt file

让我们分开参数:

$ sed -i -r 's/(foo|bar)=0//g' file

现在没关系,file不再拥有此内容:

$ cat file                         
This is example output of the test.txt file 
This is filenother example output of the  test.txt file