Bash script: Sort a large directory into alphabetical subdirectories

Every so often, I download something off the internet that is delivered as a multitude of files in a root folder, with no kind of sorting applied to it. Big sets of games for the PICO-8 engine, perhaps, or an assorted collection of music files. Often times these sets, especially if they are games, will go onto an embedded device like a modified games console, a flash cart, or onto an emulation handheld, which makes browsing 7349 files a nightmare using only a D-pad on a small screen. The device might not even support showing more than a specific number of files in one directory.

The solution? This Bash script! The script will create folders named 0-9 and A through Z, and move all files that start with a number or letter into its respective folder. At the end, you'll end up with a clean directory structure you can copy to your storage media, and not have to flick through hundreds of pages just because you want to play something that starts with a W.

Usage: cd to the directory containing your unsorted files, then execute the script. Files that do not start with a number or letter will not be moved.

foldersort.sh:

#!/bin/bash
shopt -s nocasematch
dirs=(0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z)

for file in *
do
    for dir in "${dirs[@]}"
    do
        mkdir -p "$dir"
        if [[ $file =~ ^[$dir] ]]
        then
            mv "$file" "$dir"
            break
        fi
    done
done

Comments

  1. Markdown is allowed. HTML tags allowed: <strong>, <em>, <blockquote>, <code>, <pre>, <a>.