tags:

views:

336

answers:

4

I have several thousand ebooks that need to be organized on a headless linux server running bash through SSH. All of the ebooks are thankfully named with one of 2 conventions.

AuthorFirstName AuthorLastName - Book Title.pdf

AuthorFirstName AuthorLastName - Book Series #inSeries - Book Title.pdf

i.e. Andrew Weiner - Changes.pdf

Allan Cole - Timura Trilogy 01 - When the Gods Slept.pdf

What I would like to do is to move all of the books into an organized system such as:

`DestinationDirectory/FirstLetterOfAuthorFirstName/Author Full Name/pdf's`

i.e. /books/A/Allan Cole/Allan Cole - Timura Trilogy 01 - When the Gods Slept.pdf

/books/A/Andrew Weiner/Andrew Weiner - Changes.pdf

I need help with how to put this all into a bash script that will grab the filenames of all the PDF files in the current directory, and then move the files to the proper directory, creating the directory if it doesn't already exist.

+6  A: 
for f in `ls *.pdf`; do
    name=`echo "$f"|sed 's/ -.*//'`
    letter=`echo "$name"|cut -c1`
    dir="DestinationDirectory/$letter/$name"
    mkdir -p "$dir"
    mv "$f" "$dir"
done
chaos
Thank you! That worked out beautifully!sed and cut are programs that I haven't worked with previously, I can see that they are things I should learn
Aevum Decessus
The nested `ls` command is unnecessary. This is more than adequate: `for f in *.pdf; do ...` I keep wondering why people use `ls` in this way.
greyfade
@greyfade the reason why the ls is there is because otherwise the script will error/fail out if there are no PDF files in the current working directory when it is run
Aevum Decessus
A: 

Actually found a different way of doing it, just thought I'd post this for others to see/use if they would like.

#!/bin/bash
dir="/books"
if [[ `ls | grep -c pdf` == 0 ]]
then
        echo "NO PDF FILES"
else
        for src in *.pdf
        do
                author=${src%%-*}
                authorlength=$((${#author}-1))
                letter=${author:0:1}
                author=${author:0:$authorlength}
                mkdir -p "$dir/$letter/$author"
                mv -u "$src" "$dir/$letter/$author"
        done
fi
Aevum Decessus
+1  A: 
Idelic
A: 

@OP you can do it with just bash

dest="/tmp"
OFS=$IFS
IFS="-"
for f in *.pdf
do
    base=${f%.pdf}
    letter=${base:0:1}
    set -- $base
    fullname=$1
    pdfname=$2
    directory="$dest/$letter/$fullname"
    mkdir -p $directory
    cp "$f" $directory
done
IFS=$OFS
ghostdog74