psykoblast psykoblast - 1 year ago 67
Bash Question

bad behavior of tr function while passing 2 arguments

I would like to change a parameter 1 by a parameter 2 but the output is not correct

getline="hello mr XXX";
echo $getline | tr "XXX" "$name" ;

the output is : "hello mr MMM"

do you have an idea ?

Answer Source

tr command maps character to character on a 1-to-1 basis i.e X in input is mapped to M in replacement (the last mapping).

to replace XXX with the value of variable NAME you can use sed or parameter substitution like this:

$ sed 's/XXX/'"$name"'/g' <<< "hello mr XXX"
hello mr NAME


$ echo ${getline//XXX/$name}
hello mr NAME
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download