引言
在我们之前的文章里,我们已经讲过怎么去数一个目录里文件和子目录的总数。这篇指南会教你在 Linux 系统里,把所有文件和目录的名字改成小写字母。
做到这件事有好几种方法,我们会介绍其中两种最有效、最靠谱的办法。为了方便说明,我们用了一个叫 Files 的目录,它的结构是这样的:
# find Files -depth
1. 结合 find、xargs 和 rename 命令使用
rename 是一个简单好用的命令行工具,能在 Linux 上一次改名多个文件。你可以把它和 find 工具搭配起来,用下面的方法,把某个目录里所有的文件或子目录的名字改成小写:
$ find Files -depth | xargs -n 1 rename -v 's/(.*)\/([^\/]*)/\\/\L$2/' {} \;
上面命令里用到的选项解释:
- -depth – 先显示目录里的内容,再显示目录本身。
-n 1 – 告诉 xargs 从 find 的输出中,每次命令只处理一个参数。
在 Files 目录里把文件和子目录的名字改成小写后的示例输出。
还有一种替代方法,用 find 和 mv 命令写个脚本就能搞定,具体如下。
2. 用 Shell 脚本结合 find 和 mv 命令
首先得写一个脚本:
$ cd ~/bin
$ vi rename-files.sh
然后在下面添加代码。
#!/bin/bash
#print usage
if [ -z $1 ];then
echo "Usage :$(basename $0) parent-directory"
exit 1
fi
#process all subdirectories and files in parent directory
all="$(find $1 -depth)"
for name in ${all}; do
#set new name in lower case for files and directories
new_name="$(dirname "${name}")/$(basename "${name}" | tr '[A-Z]' '[a-z]')"
#check if new name already exists
if [ "${name}" != "${new_name}" ]; then
[ ! -e "${new_name}" ] && mv -T "${name}" "${new_name}"; echo "${name} was renamed to ${new_name}" || echo "${name} wasn't renamed!"
fi
done
echo
echo
#list directories and file new names in lowercase
echo "Directories and files with new names in lowercase letters"
find $(echo $1 | tr 'A-Z' 'a-z') -depth
exit 0
保存并关闭文件,然后使脚本可执行并运行:
$ chmod +x rename-files.sh
$ rename-files.sh Files #Specify Directory Name
总结
这篇指南里,教了你怎么在 Linux 里把所有文件和目录的名字改成小写。
动动您发财的小手点个赞吧!欢迎转发!
本文由mdnice多平台发布
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。