目前我有以下 bash 脚本,它在目录中执行 for 循环:
for filename in *-example99.jpg
do
width=$(identify -format "%w" "$filename")
myVar="newName$width"
new=$(echo $filename | sed -e 's/\.jpg$/"$myVar".jpg/')
echo "$filename" "$new"
mv "$filename" "$new"
done
实际上,我想将文件重命名为:
myfilename-example99.jpg
到:
myfilename-newName.jpg
我怎样才能实现这个目标?
答案1
您不需要调用 sed:bash 参数替换可以处理此任务。尝试这个:
suffix="-example99.jpg"
for filename in *"$suffix" # wildcard * must remain unquoted
do
width=$(identify -format "%w" "$filename")
new="${filename%$suffix}-newName${width}.jpg"
echo mv "$filename" "$new"
done
${filename%$suffix}
从字符串末尾删除后缀。看https://www.gnu.org/software/bash/manual/bash.html#Shell-Parameter-Expansion
答案2
简单地与prename
(珀尔 rename
):
myVar="newName"
prename 's/-[^-.]+(\.jpg)$/-'"$myVar"'$1/' *-example99.jpg