psykoblast psykoblast - 1 month ago 8
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

#!/bin/sh
getline="hello mr XXX";
name="NAME";
echo $getline | tr "XXX" "$name" ;


the output is : "hello mr MMM"

do you have an idea ?

Answer

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

OR

$ echo ${getline//XXX/$name}
hello mr NAME
Comments