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

发布于 2021-02-02 11:14:48

谁能推荐一种安全的解决方案,从给定的根目录开始,用文件名和目录名中的下划线递归替换空格?例如:

$ 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
关注者
0
被浏览
83
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    使用rename(aka 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' "{}" \;
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看