所以我从文件名中删除特殊字符并替换为空格。除了其中包含单个反斜杠的文件之外,我都在工作。 请注意,这些文件是在 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/