StillLearningHowtodoit
StillLearningHowtodoit

Reputation: 141

Replace multiple given string with others

I have a text file like this :

Stone, John
Priya, Ponnappa
Wong, Natalie
Stanbrige, Natalie
Lee-Walsh, Natalie
Li, Natalie
Ithya, Ruveni
French, Tamzyn
Simoes, Salome
Virtue, Jackie
Campbell-Gillies,Jackie
Anderson, John
Kazantzis, John
Blair, Ruveni
Meldrum, Jackie
Smith, Maureen 
Burch, Ruveni
Harry, Verona
Andrews, Ruveni
Ellawala, Ruveni

I was able to do it with sed, but i don't found it pretty :

  sed 's/Ruveni/Ahmed/g' | sed 's/Verona/Sandro/g' | sed 's/Natalie/Chloé/g' | sed 's/John/Holly/g' | sed 's/Jackie/Melissa/g'

This will do the work by replacing the name, is there a more clean way to do it with sed or better with awk ?

Thank you soo much

Upvotes: 0

Views: 76

Answers (1)

RavinderSingh13
RavinderSingh13

Reputation: 133650

In case you want to go with key value pair approach then you could try following.

awk '
BEGIN{
  FS=OFS=", "
  array["Ruveni"]="Ahmed"
  array["Verona"]="Sandro"
  array["Natalie"]="Chlo"
  array["John"]="Holly"
  array["Jackie"]="Melissa"
}
{
  for(i=1;i<=NF;i++){
    $i=$i in array?array[$i]:$i
  }
}
1
' Input_file

OR why not simply combine all your sed substitutions separated with ; like following:

sed '
s/Ruveni/Ahmed/g;
s/Verona/Sandro/g;
s/Natalie/Chlo/g;
s/John/Holly/g;
s/Jackie/Melissa/g;
' Input_file

Upvotes: 1

Related Questions