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

Share your thoughts, leave a comment!