How to batch rename files to random characters?

Solution 1:

The following script assumes that the photos to be renamed are in your Pictures folder. This will rename every file in your Pictures folder to a 10 character random string of letters and numbers while keeping the file extensions intact.

#!/bin/bash

chars=( {a..z} {A..Z} {0..9} )

function rand_string {
    local c=$1 ret=
    while((c--)); do
        ret+=${chars[$((RANDOM%${#chars[@]}))]}
    done
    printf '%s\n' "$ret"
}

for file in ~/Pictures/*
do
    ext=$(echo ${file} | sed 's,^.*\(\.[^\.]*$\),\1,')
    mv "$file" ~/Pictures/"$(rand_string 10)"${ext}
done

If the files to be renamed are not in your Pictures folder then edit ~/Pictures accordingly. The ~ is simply a shortcut for the users home directory. So ~/Pictures = /Users/YourUsername/Pictures. Note that the * tells the script to match any file found in ~/Pictures. Also note that you can change the number of characters generated by changing the number 10 of (rand_string 10)to any number you like.

  • Copy and paste this into a plain text file and name it something like: rename_pics.sh

  • Open your Terminal (use spotlight to find it if you don't know it's location)

  • In your Terminal type chmod 755 rename_pics.sh and press Enter

  • Then type ./rename_pics.sh in your terminal and press Enter to run the script.

Solution 2:

Copy and paste this into a text file:

#!/bin/bash

cd "$1"
for i in ./*; do
    mv "$i" $((RANDOM * 32768 + RANDOM))
done

Run the following command to make the file executable (assuming you've saved the file as randomlyrename):

chmod 755 randomlyrename

And run the file:

./randomlyrename /path/to/folder/containing/things-to-rename

Bear in mind that it'll rename everything in the directory it's provided to a string of random numbers ten digits long.