如何使用 bash 脚本替换文件名中的空格

新手上路,请多包涵

任何人都可以推荐一个安全的解决方案,从给定的根目录开始递归地用下划线替换文件和目录名称中的空格吗?例如:

 $ 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

原文由 armandino 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 861
2 个回答

使用 rename (又名 prename )这是一个 Perl 脚本,可能已经在您的系统上。分两步进行:

 find . -name "* *" -type d | rename 's/ /_/g'    # do the directories first
find . -name "* *" -type f | rename 's/ /_/g'

基于 Jürgen 的 回答,并且能够使用 /usr/bin/rename (Perl 脚本)的“Revision 1.5 1998/12/18 16:16:31 rmb1”版本在一个范围内处理多层文件和目录:

 find /tmp/ -depth -name "* *" -execdir rename 's/ /_/g' "{}" \;

原文由 Dennis Williamson 发布,翻译遵循 CC BY-SA 4.0 许可协议

我用:

 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

原文由 Naidim 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题