3

does bash support multiple strings replacement on a variable at once?

on a variable (example V variable) I want to replace XXXXXXX with a string1, YYYYY with a string2 and ZZZZZZZ with a string3

Is it possible to run 1 such relpacement command instead of the 3 run below?

$ V="AAAAAAA/XXXXXXX/BBBBBB/YYYYY/CCCCCC/ZZZZZZZ"
$ V=${V//XXXXXXX/string1}
$ V=${V//YYYYY/string2}
$ V=${V//ZZZZZZZ/string3}
$ echo $V
AAAAAAA/string1/BBBBBB/string2/CCCCCC/string3
$
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Chris
  • 939
  • 2
  • 11
  • 22

3 Answers3

2

It's easier if you use sed.

V=$(echo $V | sed -e 's/XXXXXXX/string1/' -e 's/YYYYY/string2/' -e 's/ZZZZZZZ/string3/')
Tripp Kinetics
  • 5,178
  • 2
  • 23
  • 37
1

Yes you can do it like below:-

V=$(echo "$V" | sed 's/XXXXXXX/string1/g;s/YYYYY/string2/g;s/ZZZZZZZ/string3/g')

How will it work? sed command will search for sting XXXXXX and replace it with string2, replace string YYYYYY with string2 and finally replace ZZZZZZZ with string3 and store the new string into variable V.

So now check the result like below:-

echo $V
Abhijit Pritam Dutta
  • 5,521
  • 2
  • 11
  • 17
1

@Abhijit's answer is very OK (the sed option /g corresponding to the Bash // substitution for replacing all occurrences) but note that in Bash you can avoid the echo and the pipe by doing:

V=$(sed -e 's/XXXXXXX/string1/g;s/YYYYY/string2/g;s/ZZZZZZZ/string3/g' <<< $V)

This feature is actually called a here string.

ErikMD
  • 13,377
  • 3
  • 35
  • 71