grep和sed仍然与文件的其余部分重新连接

grep和sed仍然与文件的其余部分重新连接,sed,grep,awk,perl,Sed,Grep,Awk,Perl,我有一个文本文件,有n行-我想找到与特定文本匹配的行,如果匹配,则替换该行中的一些文本 foo is good foo is bad foo foo is the thing the thing is good foo - 在这个例子中,我唯一想做的就是在最后两行中替换foo,因为grep匹配thing,所以我想得到的结果是: foo is good foo is bad __ __ is the thing the thing is good __ 将grep和sed组合在一个适当的命令中

我有一个文本文件,有n行-我想找到与特定文本匹配的行,如果匹配,则替换该行中的一些文本

foo is good
foo is bad
foo foo is the thing
the thing is good foo
-

在这个例子中,我唯一想做的就是在最后两行中替换foo,因为grep匹配thing,所以我想得到的结果是:

foo is good
foo is bad
__ __ is the thing
the thing is good __

grep
sed
组合在一个适当的命令中:

与:

输出
sed
基本语法的一个重要部分是与每个命令关联的地址。如果该值为空,则该命令应用于每一行,否则,该命令仅应用于由地址选择的行。这似乎直接说明了你想做什么

然而,“地址”是一个潜在的误导性术语。尽管它可以是行号或行号范围,但它通常采用正则表达式的形式,其结果是关联的命令仅应用于与正则表达式匹配的行,其他行保持不变

因此,实现目标的一个简单方法是:

sed '/thing/ s/foo/__/g'
不需要单独的
grep
,因此也不需要将修改的行合并回原始文件中——整个更新的文件将由
sed
发出。您可以添加
sed
-i
选项以就地更新原始文件(还需要将输入文件名添加到命令行),或将输出重定向到新文件(允许将输入管道化到
sed
或指定一个或多个输入文件名)

sed '/thing/s/foo/__/g' file
#    <grep ><        >
#           substitution    
awk '/thing/{gsub(/foo/, "__")}1' file
perl -pe 's/foo/__/g if /thing/' file
foo is good
foo is bad
__ __ is the thing
the thing is good __
sed '/thing/ s/foo/__/g'