Monomoni
Monomoni

Reputation: 435

How do I sed only matched grep line

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

Upvotes: 0

Views: 498

Answers (2)

Kusalananda
Kusalananda

Reputation: 15613

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.

Upvotes: 0

Ed Morton
Ed Morton

Reputation: 203664

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

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

Upvotes: 2

Related Questions