Search code examples
macosshellfile-rename

OS X - Batch add prefix to files depending on filename length


I have a textlist with thousands of psd files which all have either 7 or 8 digits in front of the first underscore seperator in the filename.

Depending on the number of digits I need to prefix the file with either "X0" (7 digits) or Y (8 digits) so I end up with files which have identical lengths before the first underscore.

Example:

<br />0123456_this_is_file_1.psd
<br />0654321_this_is_file_2.psd
<br />30301234_this_is_file_3.psd
<br />50509876_this_is_file_4.psd

After the prefix addition the filename would be like this:

<br />X00123456_this_is_file_1.psd
<br />X00654321_this_is_file_2.psd
<br />Y30301234_this_is_file_3.psd
<br />Y50509876_this_is_file_4.psd

How can this be done in a shell script (OS X Sierra)?


Solution

  • I don't know what is the shell over OS X Sierra but this work for ksh and probably bash

    while read line; do
         l=`echo "$line" | cut -d "_" -f 1`
         if [ ${#l} -eq 7 ]; then
              mv "$line" "X0$line"
         elif [ ${#l} -eq 8 ]; then
              mv "$line" "Y$line"
         else
              echo "Error with file $line"
         fi
    done < $1
    

    This rename the files listed in your textlist according to the length of their first digits.

    Let me know if you want more explanation about how the script works.