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

我需要为此写一个shell脚本。谁能建议一下怎么开始?


当前回答

另一种选择是:

for i in *001.jpg
do
  echo "mv $i yourstring${i#*001.jpg}"
done

删除回声后,你有它的权利。

使用#的参数替换将只保留最后一部分,因此您可以更改它的名称。

其他回答

for file in *.jpg ; do mv $file ${file//IMG/myVacation} ; done

再次假设你所有的图像文件都有字符串“IMG”,你想用“myVacation”替换“IMG”。

使用bash,可以直接使用参数展开转换字符串。

例如:如果文件为IMG_327.jpg,则执行mv命令,就像执行mv IMG_327.jpg myVacation_327.jpg一样。这将对目录中匹配*.jpg的每个文件执行此操作。

myVacation_001.jpg myVacation_002.jpg myVacation_1023.jpg 等等……

find . -type f | 
sed -n "s/\(.*\)factory\.py$/& \1service\.py/p" | 
xargs -p -n 2 mv

Eg将重命名CWD中所有以“factory.py”结尾的文件,将其替换为以“service.py”结尾的文件。

解释:

In the sed cmd, the -n flag will suppress normal behavior of echoing input to output after the s/// command is applied, and the p option on s/// will force writing to output if a substitution is made. Since a sub will only be made on match, sed will only have output for files ending in "factory.py" In the s/// replacement string, we use "& " to interpolate the entire matching string, followed by a space character, into the replacement. Because of this, it's vital that our RE matches the entire filename. after the space char, we use "\1service.py" to interpolate the string we gulped before "factory.py", followed by "service.py", replacing it. So for more complex transformations youll have to change the args to s/// (with an re still matching the entire filename)

示例输出:

foo_factory.py foo_service.py
bar_factory.py bar_service.py

我们使用带-n 2的xargs一次性消耗sed 2分隔字符串的输出,并将它们传递给mv(我还在那里放置了-p选项,以便您在运行时感到安全)。瞧。

注意:如果你面临更复杂的文件和文件夹场景,这篇文章会更详细地解释find(和一些替代方案)。

不能评论Susam Pal的回答,但如果你在处理空格,我会用引号括起来:

for f in *.jpg; do mv "$f" "`echo $f | sed s/\ /\-/g`"; done;

在这个例子中,我假设你所有的图像文件都以“IMG”开头,你想用“VACATION”替换“IMG”

解决办法:先识别所有JPG文件,然后替换关键字

find . -name '*jpg' -exec bash -c 'echo mv $0 ${0/IMG/VACATION}' {} \; 

可以使用重命名实用程序按模式重命名多个文件。例如,下面的命令将字符串MyVacation2011_前置到所有扩展名为jpg的文件中。

rename 's/^/MyVacation2011_/g' *.jpg

or

rename <pattern> <replacement> <file-list>