cybrkyd

Linux bulk rename to random filenames

 Sat, 18 May 2024 17:19 UTC
Linux bulk rename to random filenames
Image: CC BY 4.0 by cybrkyd

Linux operating systems are not short of novel ways of renaming files. My favourite is via the command line using the mv command with a twist.

Say I have folder containing images with different extensions: .jpg, .jpeg, .png and so on. What would be the quickest — and arguably, the easiest — way to bulk rename these?

for f in *.jpeg; do mv "$f" $(head /dev/urandom | tr -dc a-z0-9 | head -c 10).jpeg; done

To explain:

You can also add a prefix before the string:

prefix_$(head /dev/urandom | tr -dc a-z0-9 | head -c 10).jpeg;

Why I prefer this method above anything else is because it reduces the chances of collision. Someone check my maths please — I calculate 1036 or 3.6 quadrillion combinations of 10-character names. Having experienced data loss before, especially where files are renamed sequentially as 01..02..03, random reduces that collision risk considerably.

Another point to note is file extensions. To rename all files in a folder where there are multiple extensions (e.g. .jpg, .jpeg, .png) things get a little more complicated and require a bash script to consider the differences. For that situation, I simply re-run the above and change the file extension to target the next file-type.

For added peace of mind, I always make a copy of the folder, run the rename and check the number of files remaining is the same as when I started.

»
Tagged in: #Linux

Visitors: Loading...