我如何sed只匹配的grep行 [英] How do I sed only matched grep line
问题描述
我只想在两个其他变量匹配的情况下替换一个变量。例如,我在data.txt中有这个:
I want to replace a variable only if two other variables matches. For Example I have this in my data.txt:
Mary Jane:Runs:Pasta
Mary Jane:Kicks:Apricot
John:Runs:Pasta
我只想替换一行与两个值都匹配。假设我希望第一个变量匹配Mary Jane,第二个匹配Runs,然后将该特定行从运行更改为睡眠,所以这应该是结果:
And I want to replace one variable only on the line which matches with both value. Say I want the first variable to match "Mary Jane" and the second to match "Runs" and then change that particular line from "Runs" to "Sleep", so this should be the result:
Mary Jane:Sleeps:Pasta
Mary Jane:Kicks:Apricot
John:Runs:Pasta
But I get this instead:
Mary Jane:睡觉:面食
Mary Jane:踢:杏
John:睡觉:面食
Mary Jane:Sleeps:Pasta
Mary Jane:Kicks:Apricot
John:Sleeps:Pasta
推荐答案
这里有两个解决方案。一个使用 sed
,另一个使用 awk
。两者都使用shell变量 who
和 what
(这些帮助我们找到需要更改的行)
Here are two solutions. One using sed
and another using awk
. Both makes use of the shell variables who
and what
(these helps us find the line(s) that needs changing).
who="Mary Jane"
what="Runs"
sed "s/^$who:$what:/$who:Sleeps:/" data.in
awk -vwho="$who" -vwhat="$what" -F':' \
'BEGIN { OFS = FS } $1 == who && $2 == what { $2 = "Sleeps" } 1' data.in
sed
示例使用双引号使shell扩展替换命令中的变量,而 awk
示例将通过在命令行上将Awk变量赋值给Awk变量,将shell变量转换为Awk脚本。
The sed
example makes use of double quotes to get the shell to expand the variables in the substitution command, while the awk
example transfers the values of the shell variables into the Awk script by means of assigning them to Awk variables on the command line.
这篇关于我如何sed只匹配的grep行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!