Add random string to the name of the files


I'm developing a Bash script that takes all the images I have in the folder and adds a random string before the extension. That random string would be different for each file.

The images are something like "01.jpg", "02.jpg" ... And the idea would be that when running this command they become "01- (randomstring) .jpg", "02- (randomstring) .jpg ", etc. Ex: 01-9FbdHbpitN.jpg

  • 01.jpg → 01-9FbdHbpitN.jpg

This is what I have so far:

for f in *.jpg; do printf '%s\n' "${f%.jpg}abcd.jpg"; done

But just add "abcd" at the end and I would like to be able to change that "abcd" to a self-generated hash, any random string. How could I do it?

asked by Santiago D'Antuoni 08.02.2018 в 17:41

2 answers


You can use:


for f in *.jpg; do
    random_string=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 4 | head -n 1);
    printf "%s %s\n" "$f" "$nuevo_nombre"

You have to do all those operations with pipe because otherwise dev/urandom keeps generating strings forever.

With this loop it can happen that the string of 4 random characters is repeated. But since all your images have different names, I guess it does not matter much.

Bonus Track (thanks fedorqui ) When you check that the output is correct, replace printf with mv and thus each file will be renamed.

answered by 08.02.2018 в 19:21

You can also use uuidgen to generate a Unique Universal Identifier or UUID (by its initials in English):

$ ls -l *.jpg
-rw-rw-r-- 1 cesar cesar 158153 Jan 26 14:28 01.jpg
-rw-rw-r-- 1 cesar cesar  33124 Apr 28  2016 02.jpg
-rw-rw-r-- 1 cesar cesar  57091 Mar 21  2017 03.jpg

$ for f in *.jpg; do echo $f; done;

$ for f in *.jpg; do uuid=$(uuidgen); echo "${f%.jpg}-$uuid.jpg"; done;

To move it we finally use mv replacing it with echo :

$ for f in *.jpg; do uuid=$(uuidgen); mv $f "${f%.jpg}-$uuid.jpg"; done;

$ ls -l *.jpg
-rw-rw-r-- 1 cesar cesar 158153 Jan 26 14:28 01-2821f254-98a3-41ac-be76-169b9a348e19.jpg
-rw-rw-r-- 1 cesar cesar  33124 Apr 28  2016 02-ace02d58-ff12-4798-93c9-eb258a80195b.jpg
-rw-rw-r-- 1 cesar cesar  57091 Mar 21  2017 03-afe5310b-e7d5-4966-a88f-432aaec4caba.jpg
answered by 21.02.2018 в 23:31