4
Apr

Script to Batch Random Rename Files

I used this script the other day when I wanted to randomize a group of photos from within my current working directory in the terminal (so my digital photo frame displayed randomly instead of sequentially). You could certainly spend some extra time making this more robust, but it suited my needs. You’ll probably want to modify it a bit to suit yours.

Edit: Thanks to the commenter “thewanderer”, I revisited this script to solve the issue of duplicate $RANDOM values. Now, there’s a recursive function added so files won’t be overwritten!

#!/bin/sh

if [ $# -lt 1 ]; then
   echo "Example Usage: $0 /dev/sdb"
   exit 1
fi

DIR=$1

rename(){
   rand=$RANDOM
   if [ -f "${rand}.JPG" ]; then
      rename "$i"
   else
      mv "$i" "${rand}.JPG"
   fi
}

echo "This will rename all files randomly in $DIR"
echo -e "Continue?  ( y/n ) : c"
read answer
if [ "$answer" = "n" ] || [ "$answer" = "N" ]
then
   echo "Exiting..."
   exit 1
else
(
   cd $DIR
   for i in *.JPG; do rename "$i"; done
   cd -
) >/dev/null 2>&1 </dev/null

   echo "Files have been renamed with a random number."
fi

Feel free to donate if this post prevented any headaches! Another way to show your appreciation is to take a gander at these relative ads that you may be interested in:


There's 3 Comments So Far

  • thewanderer
    June 16th, 2011 at 1:33 pm

    It’s great until you realise some files can be overwritten when there is a $RANDOM collision. A sanity check would be really nice. As always, run this on copies only, not original files 😛

  • [email protected]
    June 16th, 2011 at 2:28 pm

    Good call. That thought hadn’t even crossed my mind. A quick if statement should take care of the overwriting problem.

  • [email protected]
    June 17th, 2011 at 10:47 pm

    I updated the script so that it won’t overwrite another file should $RANDOM not be so random. 🙂 It’s safe(r) to run it now.

Share your thoughts, leave a comment!