Velvet Star Monitor

Standout celebrity highlights with iconic style.

news

How to change names of files in a directory to random generated names?

Writer Sophia Terry

I have many files with different names of different lengths. Extension of these files are jpeg.

How to change names of the files to random generated names?

3 Answers

Run in the directory with the files:

for file in *.jpeg; do mv -- "$file" "$RANDOM.jpeg"
done

But there is a chance the random names will conflict since $RANDOM only gives numbers between 0 and 32767.

Better solution, thanks to pbhj:

for file in *.jpeg; do mv -- "$file" "$(mktemp --dry-run XXXXXXXX.jpeg)"
done

There is still a chance the random names will conflict, but it's significantly smaller with 8 alphanumeric characters from mktemp. See Anselmo's answer for guaranteeing no conflicts.

5

Using RANDOM is a limited approach. From BASH man: "RANDOM Each time this parameter is referenced, a random integer between 0 and 32767 is generated." So... No more than 32768 files! : )

Another, bigger, problem is the possibility of repetition. You see, the problem of repetition affect any use of random generators, only with different probability of occurrence.

The use of mktemp can be a much better solution, but you must not use the --dry-run parameter, because this generate the name but does not guarantee that a file with that name doesn't exist. Used in that way it became only a kind of random generator.

So, my simple propose is:

for file in *.jpeg; do new_file="$(mktemp XXXXXXXX.jpeg)" mv -f -- "$file" "$new_file"
done

Step by step.

new_file="$(mktemp XXXXXXXX.jpeg)"

Running mktemp that way, it creates a file safely with a new random name, caring random repetition. It also output the name of the created file, that I catch in new_file.

mv -f -- "$file" "$new_file"

Running the mv with the -f force the renaming of the image to overwrite the new_file.

1

You can do this easily with a large degree of certainty that you won't get file names with similar names by having multiple$RANDOMs as follow:

for file in *.jpeg; do mv -- "$file" "$RANDOM-$RANDOM-$RANDOM.jpeg"
done

The possibility of getting the same name is 1/(32767)^3 in the above example.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy