Search code examples
bashcygwinfile-rename

How to add leading zero's to sequential file names


I have images files that when they are created have these kind of file names:

Name of file-1.jpg Name of file-2.jpg Name of file-3.jpg Name of file-4.jpg ..etc

This causes problems for sorting between Windows and Cygwin Bash. When I process these files in Cygwin Bash, they get processed out of order because of the differences in sorting between Windows file system and Cygwin Bash sees them. However, if the files get manually renamed and numbered with leading zeroes, this issue isn't a problem. How can I use Bash to rename these files automatically so I don't have to manually process them. I'd like to add a few lines of code to my Bash script to rename them and add the leading zeroes before they are processed by the rest of the script.

Since I use this Bash script interchangeably between Windows Cygwin and Mac, I would like something that works in both environments, if possible. Also all files will have names with spaces.


Solution

  • You could use something like this:

    files="*.jpg"
    regex="(.*-)(.*)(\.jpg)"
    for f in $files
    do
        if [[ "$f" =~ $regex ]]
        then
            number=`printf %03d ${BASH_REMATCH[2]}`
            name="${BASH_REMATCH[1]}${number}${BASH_REMATCH[3]}"
            mv "$f" "${name}"
        fi
    done
    

    Put that in a script, like rename.sh and run that in the folder where you want to covert the files. Modify as necessary...

    Shamelessly ripped from here:
    Capturing Groups From a Grep RegEx

    and here:
    How to Add Leading Zeros to Sequential File Names