Move files to directories based on first part of filename? Move files to directories based on first part of filename? bash bash

Move files to directories based on first part of filename?


for f in *.pdf; do    name=`echo "$f"|sed 's/ -.*//'`    letter=`echo "$name"|cut -c1`    dir="DestinationDirectory/$letter/$name"    mkdir -p "$dir"    mv "$f" "$dir"done


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

#!/bin/bashdir="/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"        donefi


@OP you can do it with just bash

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