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

查看:135
本文介绍了如何使用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的答案,并且能够使用/usr/bin/rename版本的"Revision 1.5 1998/12/18 16:16:31 rmb1"在一个绑定中处理多层文件和目录(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天全站免登陆