单词的正则表达式排除具有另一个单词的行

时间:2014-01-27 10:18:38

标签: regex sed awk grep

输入:

hello world.
This is hello world.
Another hello world.
New hello world.

现在搜索hello的所有匹配项,不包括包含This

的行

搜索输出:

hello world
Another hello world
New hello world.

现在用hello

替换所有hell

替换输出:

hell world.
This is hello world.
Another hell world.
New hell world.

4 个答案:

答案 0 :(得分:2)

您可以使用awk执行此操作

awk '/hello/ && !/This/ {gsub(/hello/,"hell")}8' file
hell world.
This is hello world.
Another hell world.
New hell world.

答案 1 :(得分:1)

grep不做替换,因此您需要使用其他工具。 Jotne已展示了如何使用awk执行此操作,以下是sed的使用方法:

sed -e '/This/b' -e '/hello/ s/hello/hell/' file

输出:

hell world.
This is hello world.
Another hell world.
New hell world.

答案 2 :(得分:1)

perl -pi -e 's/hello/hell/g if(/hello/ && $_!~/This/)' your_file

更简单的版本:

perl -pi -e 's/hello/hell/g unless(/This/)' your_file

下面测试:

> cat temp
hello world.
This is hello world.
Another hello world.
New hello world.
> perl -pe 's/hello/hell/g unless(/This/)' temp
hell world.
This is hello world.
Another hell world.
New hell world.
> 

答案 3 :(得分:1)

为什么不简单地这样做:

sed '/This/!s/hello/hell/g'

还是我误解了这个要求?它给出了:

hell world.
This is hello world.
Another hell world.
New hell world.