Program/command to batch rename images with random file names?

EDIT: There are lots of wonderful solutions below, but I’m only allowed to choose “one” as the official. If you’re looking for the solution to a similar problem, by all means, read all of the comments. There’s some great ideas down there.

I have various .jpg and .png images in folders and I’d like to give them random file names so that they can be in a random order. I also want the process to be lossless (not deleting a file because it accidentally gets the same name).

I’d really prefer something with a gui to do this because I’m not great with terminal (but I go there fine when the need is there).

So, if there’s no gui way to do this, if I were to right click and open the folder in terminal, how would I randomly rename all of the jpg or png in one pass? I’m more than happy to do just one at a time. It’s less confusing to try to understand the code that way if I have to.

Thanks! <3

You haven’t specified which Desktop Environment you happen to be running. KDE has kRenamer which may not be installed by default, but I should imagine its easily found in the repositories. If you’re using XFCE, there is Thunar Bulk Rename Utility which works hand-in-hand with the Thunar file manager. Both of these are GUI applications and may (or may not) be what you’re looking for. Both could be installed using other DE’s, if needed. For example, you could install both Thunar and Thunar Bulk Rename Utility in KDE even though they are made for XFCE.

I’m sure there are other alternatives but these are all that come to mind.

Cheers.

1 Like

My sincere apologies. I’m using the gnome desktop.

I appreciate the suggestions and I’ll be sure to go check those out right now. I’m confident that you’re correct and that I’ll have no issues installing them even though I use different desktop environment. I’ll go investigate these and check back soon to see if the problem is solved. I surely just need random file names so they’re in random order. As long as that happens, I’m genuinely indifferent (other than easier/more user friendly, the better).

Thanks again! Going to go investigate.

Just for the exercise I create a small python script which does the thing

The script is commented explaining what it does

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# @linux-aarhus - root.nix.dk
# License: GNU GPL, version 3 or later; https://www.gnu.org/licenses/gpl.html

from pathlib import Path
import tempfile
import shutil

# -----------------------------------
# Amend this to your use case
# copy or move image ( False / True)
MOVE = False

# input folder containing the images
READ_FOLDER = f"{Path.home()}/Pictures"

# output folder to store the renamed images
WRITE_FOLDER = f"{Path.home()}/temp"

# filename glob - could be *.jpg - but only one extension will work
GLOB = "*.png"

# -----------------------------------
# This is the actual worker script
# extract extension from glob
extension = GLOB.split(".")[-1]

# create a path object
filedir = Path(READ_FOLDER)

# create a file list object using the glob
my_images = filedir.rglob(GLOB)

# loop the file list
for img in my_images:   

    # because we use tempfile which creates /tmp/randomname
    # and we do not remove the generated filename
    # the filename is guaranteed to be unique within the /tmp folder
    # so generate a temp file using tempfile
    temp_file = tempfile.NamedTemporaryFile()

    # extract the name, the last part after the last '/' and append the extension
    new_name = f"{temp_file.name.split('/')[-1]}.{extension}"

    # close the file
    temp_file.close()

    if MOVE:
        # print status message
        print(f"Move {READ_FOLDER}/{img} to {WRITE_FOLDER}/{new_name}")

        # the actual move jof original to the new file using shutil
        shutil.move(f"{READ_FOLDER}/{img}", f"{WRITE_FOLDER}/{new_name}")

        # this command continues the loop
        # making an else clause unnecessary
        continue

    # print status message
    print(f"Copy {READ_FOLDER}/{img} to {WRITE_FOLDER}/{new_name}")

    # the actual copy of the image using shutil
    shutil.copy(f"{READ_FOLDER}/{img}", f"{WRITE_FOLDER}/{new_name}")

3 Likes

I just saw krename mentioned, though I actually went back to using GPRename recently - it’s pretty good… but it won’t do ‘random’ anything…

So I opened a folder of photographs, opened the terminal pane and copied the photos, creating a ‘random’ folder to paste them into.

Opened the terminal pane, type:

for i in *.jpg; do mv -i "$i" ${RANDOM}${RANDOM}.jpg; done 

Easy enough to edit to adjust for png’s or whatever…

Don’t ask why I did $RANDOM twice - there was an issue, and I’m a dirty fixer :rofl: if you wanna know, try it yourself.

2 Likes

I’m having a difficult time making either of the “truly” random, but it is SUPER helpful being able to select batches and then being able to add prefixes to their names. I can basically accomplish the same result with a little bit of effort (but still WAY better than trying to rename them by hand). Def appreciate the recommendation. I could make these work. Thanks again!

Ah nice!! I’ll save this and make use of it when needed! Thanks for taking the time to type this up! I love how capable programmers seem to be ahahaha.

Ah nice! Need to put that line of code in a safe place! hahaha. I appreciate it.

While I don’t know anything about programming for the most part, the ${RANDOM}…I’m assuming the $ means it’s a number, and, I “assume” there’s a max integer limit on that, and that the limit is small enough to have high statistical odds of periodically double using the same number, therefore deleting the first file…and by doing it twice…you’re like…doing it twice, and the chances are virtually nonexistant now. Is that roughly right and why you say that it’s imperfect? That’s more than effective for what I’m doing. I def don’t want to lose files, but I will be working with copies of files, so the file won’t be lost. I just don’t want it to be a recurring issue, and it sounds like if what I say is true, it’d be a once in a life time experience ahahahaha.

I checked out GPRename since you brought it up. I like it, too, actually. You’re right about it not doing random. I can’t find random there, either.

While I surely prefer a GUI, it seems like the GUI options are imperfect at best, and your line of code is effective enough that I can probably live with it. Hahaha. I appreciate your time and sharing something simple enough that even I can use it.

alias randomjpg=for i in *.jpg; do mv -i "$i" ${RANDOM}${RANDOM}.jpg; done 
1 Like

If you would like random alphanumeric names that are guaranteed to never be the same (unless your computer is so fast that it can process multiple files per nanosecond in a “for” loop), and also want to process multiple image types at the same time (with case-insensitive file extensions), then here’s a little bash script that I just came up with (with a little help from online resources). You can save it to your local bin folder as “randhexname” to run as a normal command (or you can just save it within the image folder & use ./randhexname to run it). Make sure you make the script file executable.

(and yes - I know I could have left out the hex conversion, but writing the script was a learning experience for me too, and I wanted a way to get random alphanumeric values)

Here’s the script:

#!/bin/bash

# randhexname
# A script to rename image files to random alphanumeric names by
# converting the nanoseconds since epoch to hexadecimal numbers and
# reversing those numbers so that the new file names are in random
# order compared to the old file names.

# This script will keep the original file extensions & is case-insensitive.

# MAKE SURE YOU RUN THIS SCRIPT FROM WITHIN THE FOLDER WHERE THE IMAGES ARE STORED!

shopt -s nocaseglob

read -p "Image files in $PWD will be renamed. Do you want to proceed? " -n 1 -r
echo    # (optional) move to a new line

if [[ $REPLY =~ ^[Yy]$ ]]; then

for file in *.{jpg,jpeg,png}; do

ext="${file##*.}"

# get the date in nanoseconds since epoch
now=$(date +%s%N);

# convert nanosecond date to a 16-digit hex number & reverse it to randomize sort order
hexname=$(bc <<< "obase=16;${now}" | rev);

# move the file unless the new name already exists (noclobber)
mv -vn "${file}" "${hexname}.${ext}";

done

else

echo "Script is exiting"

fi

shopt -u nocaseglob

2 Likes

The only gui file renaming application I’ve ever found that would suit the use case is Bulk Rename Utility - Unfortunately it’s only for Windows.

A nicely crafted script such as the above offering from scotty65 sure beats setting up WINE for one app, though, imho. Cheers.

2 Likes

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.