【问题标题】:Using tr to replace non-alpha characters with '-' is adding an extra character to end of string使用 tr 用 '-' 替换非字母字符是在字符串末尾添加一个额外的字符
【发布时间】:2018-08-16 12:28:09
【问题描述】:

我有以下字符串hello/world 我想用- 替换/ 得到hello-world

我尝试了以下方法:http://rextester.com/NMIOL63413

$ echo hello/world | tr -c '[:alnum:]' '-'
$ hello-world-

为什么最后会有一个额外的-,我该如何摆脱它?

【问题讨论】:

  • 试试echo -n hello/world | tr -c '[:alnum:]' '-'(强调-n do not output the trailing newline)
  • 建议printf '%s' hello/world 比建议echo -n 更好;后者是非标准化的,并且可以在符合 POSIX 的平台/shell 中表现不同。请参阅pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html 的应用程序部分:除非 -n(作为第一个参数)和转义序列都被省略,否则不可能在所有 POSIX 系统中使用可移植的 echo。
  • 顺便说一句,这是为了将字符串变成安全/有效的文件名吗?您根本不需要使用echo、printf 或 tr 来达到目的:old_name=hello/world; new_name=${old_name//[^[:alnum:]]/-}; echo "$new_name" 可以在没有换行文字参与的情况下完成这个技巧(并且没有费用的fork()关闭一堆子shell来运行管道)。

标签: bash tr


【解决方案1】:

很明显echo 在每个字符串的末尾打印一个\n。由于使用-c,您正在寻找替换不属于[:alnum:] 的 部分的字符。由于换行符也不是有效字母数字字符的一部分,因此它也会被替换。

在您不确定哪个“神奇”字符存在或被替换的情况下,请执行hexdump 以查看字符串中的内容。你可以在末尾看到\n。

echo hello/world | hexdump -c
0000000   h   e   l   l   o   /   w   o   r   l   d  \n
000000c

因此,为避免换行符和其他 shell 元字符与您的替换字符串混淆,请始终使用printf:

printf '%s' 'hello/world' | tr -c '[:alnum:]' '-'

【讨论】:

  • 另一种选择是使用tr -c '[:alnum:]\n' '-',在未被替换的字符集中添加换行符。
猜你喜欢
  • 1970-01-01
  • 2017-08-02
  • 2013-03-20
  • 1970-01-01
  • 2011-04-10
  • 1970-01-01
  • 1970-01-01
  • 2020-08-12
  • 2011-09-16
相关资源
最近更新 更多