简体   繁体   English

传递2个参数时tr函数的不良行为

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM