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

发布于 2022-05-26 23:33:17

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

$ 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
被浏览
11
1 个回答
  • 面试哥
    面试哥 2022-05-26
    为面试而生,有面试问题,就找面试哥。

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

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

    基于 JUrgen 的/usr/bin/rename回答,并且能够使用“Revision 1.5 1998/12/18 16:16:31
    rmb1”版本(Perl 脚本)在单个绑定中处理多层文件和目录:

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


知识点
面圈网VIP题库

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

去下载看看