当我跑步时,echo \xc3\xa9 | tr \xc3\xa9 e我得到的ee不是e我所期待的。
这是命令的结果locale:
LANG=en_US.UTF-8\nLC_CTYPE="en_US.UTF-8"\nLC_NUMERIC="en_US.UTF-8"\nLC_TIME="en_US.UTF-8"\nLC_COLLATE="en_US.UTF-8"\nLC_MONETARY="en_US.UTF-8"\nLC_MESSAGES="en_US.UTF-8"\nLC_PAPER="en_US.UTF-8"\nLC_NAME="en_US.UTF-8"\nLC_ADDRESS="en_US.UTF-8"\nLC_TELEPHONE="en_US.UTF-8"\nLC_MEASUREMENT="en_US.UTF-8"\nLC_IDENTIFICATION="en_US.UTF-8"\nLC_ALL=\nRun Code Online (Sandbox Code Playgroud)\n
看起来tr不能很好地处理宽字符。
$ echo \'\xc3\xa9\' | od -c\n0000000 \xef\xbf\xbd \xef\xbf\xbd \\n\n0000003\n$ echo \'\xc3\xa9\' | tr \'\xc3\xa9\' e | od -c\n0000000 e e \\n\n0000003\nRun Code Online (Sandbox Code Playgroud)\n由于左侧字符集的长度为 2 个字符字节,tr因此将重复右侧字符集的最后一个字符,直到其长度相同。
$ echo 123456789 | tr 2468 xy\n1x3y5y7y9\nRun Code Online (Sandbox Code Playgroud)\n您可能更喜欢sed处理非 ASCII 字符。
$ echo \'\xc3\xa9\' | sed \'s/\xc3\xa9/e/g\' | od -c\n0000000 e \\n\n0000002\n$ echo \'\xc3\xa9\' | sed \'y/\xc3\xa9/e/\' | od -c\n0000000 e \\n\n0000002\nRun Code Online (Sandbox Code Playgroud)\n