Bash File Sorter


# This script only works specifically on files that follow a specific naming system.
# It parses the first three letters after the first position and creates directories 
# using those three letters.  It should then move the files into the directories
# whose names also start with a similar prefix.
# I.e. the file [Alpha] Bravo - Charlie - {001}.pdf should get moved into a
# directory called ./alp
# This first line takes the command input and moves it to a variable so it
# can be more easily handled.

if [ $sStartDir = "" ]; then

cd $sStartDir

# This first step gave me trouble initially; in its current state it should
# pipe the output of 'ls' into the 'read' function of the script.
# When a 'for' loop was used it only grabbed the first word of the filename.

ls -1 | while read sFilename; do
    # Evaluate filename; make sure it is sortable
    if [ $Test = "[" ]; then
        # We know it's sortable, now get the 3-letter prefix
        # Strip out the spaces
        sPrefix=${sFilename/" "/""}
        # Check whether it is an existing directory
        sPrefix=$(echo $sPrefix | tr [:upper:] [:lower:])
        if [ ! -d ./$sPrefix ]; then
            # If not, then create it
            mkdir ./$sPrefix
        # Check whether the same file exists in the destination
        if [ ! -e "./$sPrefix/$sFilename" ]; then
            # Move the file into that directory        
            mv "$sFilename" "./$sPrefix"
            echo "Error: File exists at destination: "$sFilename    

A member of a now-defunct comics forum requested a script that would sort his collection according to a specific file structure.

The script should take a directory as a parameter and sort the contents within into folders based on the three-letter prefix of the files. For this to work, the files do need to be named in that weird way comics seem to be, i.e.

[Author] Title Vol Issue.cbr

It will then create a series of subdirectories based on the author name and move the file there, i.e.


…or if the directory exists, the file will just be moved there without creating a new folder.

Project Info

Client: Anonymous


  • Scripting

Leave a Reply