1

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.

Jack Dorn
  • 13
  • 2
  • Are all the files in the same folder? Also which cygwin(cygcheck.exe -V) and what bash version on Mac? – sjsam Aug 03 '16 at 02:17
  • 1
    Oops, You forgot to post your code. StackOverflow is about helping people fix their code. It's not a free coding service. Any code is better than no code at all. I'm sure I've seen similar problems here, did you search for solutions. Use one of them, and update your Q to indicate where you're having problems. Good luck. – shellter Aug 03 '16 at 02:20

2 Answers2

1

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

Community
  • 1
  • 1
Travis Rodman
  • 607
  • 1
  • 6
  • 14
0
#!/bin/bash

#cygcheck (cygwin) 2.3.1
#GNU bash, version 4.3.42(4)-release (i686-pc-cygwin)

namemodify()
{
bname="${1##*/}"
dname="${1%/*}"
mv "$1" "${dname}/00${bname}" # Add any number of leading zeroes.
}

export -f namemodify
find . -type f -iname "*jpg" -exec bash -c 'namemodify "$1"' _ {} \;

I hope this won't break on Mac too :) good luck

sjsam
  • 21,411
  • 5
  • 55
  • 102
  • 1
    This is cool when you have single-digit file names, but if you get things like "Name of File-10.jpg" you are going to get a conversion to "Name of File-0010.jpg" instead of the assumed "Name of File-010.jpg" :/ – Travis Rodman Aug 03 '16 at 02:54