Bringing some order in your data files

Lots of harddisk space leads to…. lots of files. Why throw stuff away when keeping it is so cheap? I always end up with a gazillion files spread out, often over multiple disks.

Specifically I have this problem with image files, photos and videos.

I wrote a blog post about “flattening” a hierarchy of files a while ago, but that advice had a basic flaw. If two files had the same name, and that happens a lot with cameras naming files DSC000001.jpg, one will overwrite the other.

So my command to flatten a hierarchy of files is now this better version (Linux):

find . -mindepth 1 -type f -name "*.JPG" -exec mv --backup=t -v -t ../target-directory {} +

Note the addition of –backup=t and -v

Also note that target-directory should be OUTSIDE of the source directory, otherwise you might end up in a loop and cause an incredibel mess.

–backup=t will if there is a clash where two files are named DSC0001.jpg, the second one will be renamed DSC0001.jpg.~1~

Subseqeuent files will be renamed with ~2~, ~3~ etc etc

Thats now all and well, but you have a bunch of files without an JPG extension, and that might no be what you want.

But to the rescue comes a nifty little script that renames those files:

#!/bin/bash

shopt -s dotglob   # so we include hidden files!

# Create a directory parallell with this one where result will be

mkdir ../renumbered
num=1
for file in *.jpg; do
       mv -i "$file" "$(printf "%u" $num).jpg" ../renumbered
       let num=$num+1
done

shopt -u dotglob # back to not include hidden files

This will create 1.jpg, 2.jpg, 3.jpg and so on. If you need a different numbering scheme, you can modify the “mv” command to your liking.

IMPORTANT NOTE!

This script has a different flaw, albeit just as serious. If you use this on an existing folder, and already have files named 1.jpg, 2.jpg etc, this script will OVERWRITE them unless you have configured bash to do otherwise!

The best soluition to avoid this is to make sure that the TARGET directory is new and empty when starting!

You have to change the script accordingly

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.