通过使用 shell 脚本替换文件名中的特定模式来重命名多个文件

问题描述:

编写一个简单的脚本来自动重命名一些文件.例如,我们希望将文件 *001.jpg 重命名为用户定义的字符串 + 001.jpg(例如:MyVacation20110725_001.jpg)此脚本的用途是让数码相机照片具有有意义的文件名.>

Write a simple script that will automatically rename a number of files. As an example we want the file *001.jpg renamed to user defined string + 001.jpg (ex: MyVacation20110725_001.jpg) The usage for this script is to get the digital camera photos to have file names that make some sense.

我需要为此编写一个shell脚本.有人可以建议如何开始吗?

I need to write a shell script for this. Can someone suggest how to begin?

帮助您起步的示例.

for f in *.jpg; do mv "$f" "$(echo "$f" | sed s/IMG/VACATION/)"; done

在此示例中,我假设您的所有图像文件都包含字符串 IMG,并且您希望将 IMG 替换为 VACATION.

In this example, I am assuming that all your image files contain the string IMG and you want to replace IMG with VACATION.

shell 自动将 *.jpg 评估为所有匹配的文件.

The shell automatically evaluates *.jpg to all the matching files.

mv(文件的新名称)的第二个参数是 sed 命令的输出,该命令将 IMG 替换为 假期.

The second argument of mv (the new name of the file) is the output of the sed command that replaces IMG with VACATION.

如果您的文件名包含空格,请特别注意 "$f" 符号.您需要双引号来保留空格.

If your filenames include whitespace pay careful attention to the "$f" notation. You need the double-quotes to preserve the whitespace.