bash - 用 tr 去除反斜杠

标签 bash macos tr

所以我从文件名中删除特殊字符并替换为空格。除了其中包含单个反斜杠的文件之外,我都在工作。 请注意,这些文件是在 OS X 上的 Finder 中创建的

old_name="testing\this\folder"
new_name=$(echo $old_name | tr '<>:\\#%|?*' ' ');

这导致 new_name 成为“testing hisolder” 我怎样才能只删除反斜杠而不是前面的字符?

最佳答案

This results in new_name being "testing hisolder"

这个字符串看起来像 echo -e "testing\this\folder" 的结果,因为 \t\f 实际上替换为制表和换页控制字符

也许你有一个像 alias echo='echo -e' 这样的别名,或者你的 shell 版本中 echo 的实现解释了反斜杠转义:

POSIX does not require support for any options, and says that the behavior of ‘echo’ is implementation-defined if any STRING contains a backslash or if the first argument is ‘-n’. Portable programs can use the ‘printf’ command if they need to omit trailing newlines or output control characters or backslashes.

(来自信息页面)

所以你应该在新软件中使用printf 而不是echo。特别是,echo $old_name 应该替换为 printf %s "$old_name"

this discussion中有很好的解释,例如。

不需要printf

正如@mklement0 所建议的,您可以通过 Bash here string 来避开管道:

tr '<>:\\#%|?*' ' ' <<<"$old_name"

关于bash - 用 tr 去除反斜杠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40490062/

相关文章:

sed - 无法使用 tr、sed 从字符串中删除空格

awk - grep,剪切并从文件中删除\n

linux - 关闭ssh连接后如何保持任务运行?

bash - 计算命令行参数的总和并显示结果

python - Mac 上安装 Odoo 无法执行命令 LESSC

linux - 获取地址信息 "10 . 10 . 10 . 10"

linux - 如何连接两个 linux 命令的结果?

Bash 脚本 - 查找具有非零字节内容的目录

bash - 检查 Bash 中两个文件的大小是否不同

node.js - node-v12.16.1.pkg”无法打开,因为 Apple 无法检查它是否存在恶意软件