Reputation: 3625
I am using the following code to rename all the images in the current folder:
a=1
for i in *.jpg; do
new=$(printf "%04d.jpg" ${a}); #04 pad to length of 4
mv ${i} ${new};
a=$((a+1));
done
But I have met a problem: some of the images were overwritten, because I use it after I have added more images in the folder. Is there a way to fix this? I thought to add an if (name_exists) then next_name
, but I am new to scripts. Any help, please?
Upvotes: 4
Views: 793
Reputation: 63922
You can use:
#!/bin/bash
glob="[0-9][0-9][0-9][0-9].jpg"
last=$(find . -maxdepth 1 -name "$glob" -print |sort -gr |grep -Pom1 '\d{4}') # or |grep -om1 '[0-9][0-9]*')
last=${last:-0}
while IFS= read -d $'\0' -r image
do
let last++
echo mv "$image" "$(printf "%04s" $last ).jpg"
done < <(find . -maxdepth 1 -name \*.jpg -a -not -name "$glob" -print0)
where:
find
finds the last used numberwhile read
reads the output from thefind
what finds all .jpg
what have different name as NNNN.jpgYou can imprpve this
9999
... so...The script is in dry mode, remove the echo
when satisfied
dash version:
glob="[0-9][0-9][0-9][0-9].jpg"
last=$(find . -maxdepth 1 -name "$glob" -print |sort -gr |grep -Pom1 '\d{4}') # or |grep -om1 '[0-9][0-9]*')
last=${last:-0}
for image in *.jpg
do
echo "$image" | grep -q "^$glob$" && continue
#last=$((last+1)) #with leading zeroes, the numbers treated as octal... fails for 08 and such
last=$(expr $last + 1)
echo mv "$image" "$(printf "%04d" $last ).jpg"
done
Upvotes: 2
Reputation: 72
add the following to your script
a=1
for i in *.jpg; do
new=$(printf "%04d.jpg" ${a});
while [ -f ${new} ]
do
a=$((a+1));
new=$(printf "%04d.jpg" ${a});
done
mv ${i} ${new};
a=$((a+1));
done
if you are not too particular about the numbered names. You could use this:
if [ -f ${new} ]
then
new=$(printf "%04d_%s.jpg" ${a} $(date +'%H_%M_%S'))
fi
instead of while.
Upvotes: 0