【发布时间】:2014-08-27 09:12:33
【问题描述】:
我编写了一个脚本来一次重命名多个文件并添加前导零。 该脚本将要重命名的文件作为第一个参数,第二个是新名称,作为第三个参数,您可以提供新的扩展名
只要文件不包含空格(test asd 1.txt / test asd 2.txt),它实际上就可以工作,因为输出是:
~/Desktop $ gpRenameWithZero test\ asd\* test_ mp3
ls: cannot access test: No such file or directory
ls: cannot access asd*: No such file or directory
ls: cannot access test: No such file or directory
ls: cannot access asd*: No such file or directory
这是脚本:
#!/bin/bash
#rename a group of files with adding padding zero: gpRenameWithZero $1=filesToBeRenamed $2=newName $3=filetype: gpRenameWithZero \* newName_ jpg
#123 files -> length of number are 3 digits
numberOfDigits=$(ls $1| wc -l | xargs expr length)
#take extension from command line or take from filename
if [ $# -gt 2 ]; then
extension=$3
else
extension=$(ls -rt $1 | head -n 1 | rev | cut -d . -f1 | rev)
fi
#Preview
ls -rt $1 | cat -n | while read n f; do echo mv "$f" `printf "$2%0$numberOfDigits"d".$extension" $n`; done
read -p "Do you wish to rename [y/n]?" yn
case $yn in
[Yy]* ) ls -rt $1 | cat -n | while read n f; do mv "$f" `printf "$2%0$numberOfDigits"d".$extension" $n`; done;;
[Nn]* ) ;;
esac
我已经尝试过引用/双引号变量和参数,转义/不转义。
如何解决这个问题?还是有一个更简单的脚本,它将要重命名的文件、新名称和扩展名作为参数)来重命名多个文件。
【问题讨论】:
-
为什么不使用
rename实用程序?例如,我有时使用rename "s/ /_/g" *删除文件名中的空格
标签: linux shell file-io whitespace