How do I sed only matched grep line

不问归期 提交于 2019-12-25 08:33:05

问题


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

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:Sleeps:Pasta
Mary Jane:Kicks:Apricot
John:Sleeps:Pasta

回答1:


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

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.




回答2:


You should really use awk, not sed, for that:

awk 'BEGIN{FS=OFS=":"} ($1=="Mary Jane") && ($2=="Runs"){$2="Sleeps"} 1' file


来源:https://stackoverflow.com/questions/41657716/how-do-i-sed-only-matched-grep-line

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!