In Bash, the solution could look like this:
#!/bin/bash
shopt -s extglob
for fn_old in *.jpg; do
i=0
fn_new=${fn_old##+([-0-9])} # strip leading number sequence in basename
fn_new=${fn_new/%[-0-9]*([-0-9x]).jpg/.jpg} # strip trailing number sequence in basename
while [[ -e $fn_new ]]; do # see if proposed name already exists
i=$((i+1)) # doublure counter
fn_new=${fn_new/%*([-0-9]).jpg/-$i.jpg} # try new filename with updated number
done
echo "$fn_old" -- "$fn_new"
mv "$fn_old" "$fn_new"
done
Be careful with the mv
command. You may want to comment it out (or replace it with a cp
) on a first run, just to see if the renaming scheme is what you want/expect.
For an explanation of the shell patterns and string manipulations, see: Bash pattern matching and Bash string manipulations.