[英]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 我想通过参数2更改参数1,但输出不正确
#!/bin/sh
getline="hello mr XXX";
name="NAME";
echo $getline | tr "XXX" "$name" ;
the output is : "hello mr MMM" 输出为:“ hello mr MMM”
do you have an idea ? 你有想法吗 ?
tr
command maps character to character on a 1-to-1 basis ie X
in input is mapped to M
in replacement (the last mapping). tr
命令以tr
将字符映射到字符,即输入中的X
映射为替换中的M
(最后一个映射)。
to replace XXX
with the value of variable NAME
you can use sed
or parameter substitution like this: 将
XXX
替换为变量NAME
的值,您可以使用sed
或参数替换,如下所示:
$ sed 's/XXX/'"$name"'/g' <<< "hello mr XXX"
hello mr NAME
OR 要么
$ echo ${getline//XXX/$name}
hello mr NAME
tr
expects a 1:1 mapping between the input/ouput sets: tr
期望输入/输出集之间为1:1映射:
tr XXX NAME
123 1234
Since you have THREE identical chars in the input, only the last one is used for the mapping, and X #3 maps to character #3 in the "replacements" parameter, which happens to be M
由于输入中有三个相同的字符,因此仅将最后一个字符用于映射,并且X#3映射到“替换”参数中的字符#3,恰好是
M
If you'd expand the command out a bit more: 如果您进一步扩展命令:
$ echo hello mr XXXYZ|tr "XXXY" "NAME"
hello mr MMMEZ
Y
maps to E
, because they're both the 4th char in the in/out sets. Y
映射到E
,因为它们都是输入/输出集中的第四个字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.