如何使用 bash 脚本替换文件名中的空格 [英] How to replace spaces in file names using a bash script

查看:43
本文介绍了如何使用 bash 脚本替换文件名中的空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Can anyone recommend a safe solution to recursively replace spaces with underscores in file and directory names starting from a given root directory? For example:

$ 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

推荐答案

使用 rename(又名 prename),它是一个 Perl 脚本,它可能已经在你的系统上.分两步做:

Use rename (aka prename) which is a Perl script which may be on your system already. Do it in two steps:

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

基于 Jürgen 的回答,并且能够使用Revision 1.5 1998/12/18 16:16:31 rmb1"在单个边界中处理多层文件和目录;/usr/bin/rename 版本(Perl 脚本):

Based on Jürgen's answer and able to handle multiple layers of files and directories in a single bound using the "Revision 1.5 1998/12/18 16:16:31 rmb1" version of /usr/bin/rename (a Perl script):

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

这篇关于如何使用 bash 脚本替换文件名中的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆