谁能推荐一个安全的解决方案,从给定的根目录开始,递归地将文件和目录名中的空格替换为下划线?例如:
$ tree
.
|-- a dir
| `-- file with spaces.txt
`-- b dir
|-- another file with spaces.txt
`-- yet another file with spaces.pdf
变成:
$ tree
.
|-- a_dir
| `-- file_with_spaces.txt
`-- b_dir
|-- another_file_with_spaces.txt
`-- yet_another_file_with_spaces.pdf
最佳答案
我使用:
for f in *\ *; do mv "$f" "${f// /_}"; done
虽然它不是递归的,但它非常快速和简单。我确定这里有人可以将其更新为递归。
${f///_}
部分利用 bash 的参数扩展机制将参数中的模式替换为提供的字符串。
相关语法是${parameter/pattern/string}
。请参阅:https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html或 http://wiki.bash-hackers.org/syntax/pe .
关于linux - 如何使用 bash 脚本替换文件名中的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25637693/