Random file-names using bash/perl

A couple of times I’ve wanted to sort files in a random fashion, and allways worked around it someway sorting for size, dates or other things.

I needed a random sorting of pictures when making a slide-show for my mother.

run the following command to give the files a unique “random” 10-digit number.

ls | perl -ne 'if (/.jpg$/i) {chomp;while(-e ($n = (int(rand(10**10-1)).".jpg")) || length($n) < 14) {print "Too short: $n (" . length($n) . ")\n";} rename $_, "$n";'}
(it prints out names being to short just as info)

I also needed to group these files into some subdirectories. Run the following command to create a number of sub-directories:

for i in `seq 1 8`; do echo "creating $i"; mkdir $i; done
(it prints out the directory-names)

run this command to move the files into the sub-directories:

ls | perl -ne 'if (/.jpg$/i) {chomp; $dir = ($dir++ % 8 + 1); print "$dir\n"; rename $_, "$dir\/$_"; }' | sort -n | uniq -c
(it prints out the number of files and the name of the directories)

Leave a Reply

Your email address will not be published.
Required fields are marked:*