reorder files by renaming

To rename files the way this can list them: ls -lv

This is needed when for example you need to handle bunch of images named like:
1 front.jpg -> 0001.jpg
02.jpg-> 0002.jpg
3.jpg-> 0003.jpg
10.jpg-> 0004.jpg

Found somewhere in the net, working great. Just test with echo and remove echo when ready. Need to also fix the files with space in name.

#!/bin/bash
def=0000
for f in $(ls -v *.jpg);do
 ((cnt++))
 if [[ ! -e "${def:${#cnt}:${#def}}${cnt}.jpg" ]];then
 echo mv "${f}" "${def:${#cnt}:${#def}}${cnt}.jpg" #remove preceding echo if everything is fine
 fi
done
This entry was posted in Uncategorized. Bookmark the permalink.