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:
- 1st
find
finds the last used number
- the
while read
reads the output from the
- 2nd
find
what finds all .jpg
what have different name as NNNN.jpg
- increment and rename
You can imprpve this
- search other types of images (not only jpg)
- change the script to case insensitive
- the above will fail if the image count raises above
9999
... so...
The script is in dry mode, remove the echo
when satisfied
EDIT
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