输入:
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.
答案 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.