two7s_clash
two7s_clash

Reputation: 5827

BASH script for sorting files recursively by base filename into folders of the same name

I have the following file structure:

\HI

\LO

\MED

*base_filename*_med.mp4

\STILLS

*base_filename*_med.jpg

\CAPTIONS

*base_filename*.adb.xml

\TRANSCRIPTS

*base_filename*.txt

In order to ingest these into a MarkLogic environment, I need these rearranged to into the following structure, where asset is the base filename.

\ASSET

I would like a bash script to sort these out for me. Suggestions?

Upvotes: 2

Views: 872

Answers (1)

glenn jackman
glenn jackman

Reputation: 246774

find . -type f -print |
while read -r pathname; do
    filename=${pathname##*/}
    case "$filename" in
        *_hi* | *_med* | *_lo*)
            # strip off last underscore and following chars
            new_dirname=${filename%_*} 
            ;;
        *)
            # strip off first dot and following chars
            new_dirname=${filename%%.*} 
            ;;
    esac
    mkdir -p "../$new_dirname"
    echo mv "$pathname" "../$new_dirname/$filename"
done 

Untested. Remove the echo when you're satisfied the mv commands look correct.

I moved the destination directories to the parent dir of CWD because I'm not certain whether find will pick up the newly created directories. Can someone address this point?

Upvotes: 5

Related Questions