简体   繁体   中英

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

I have the following file structure:

\\HI

  • ActionPotential_hi.mp4
  • ADHD_hi.mp4
  • AlzheimersDisease_hi.mp4
  • alzheimers_art_hi.mp4
  • artificial_eye_hi.mp4
  • more files ...

\\LO

  • ActionPotential_lo.mp4
  • ADHD_lo.mp4
  • AlzheimersDisease_lo.mp4
  • alzheimers_art_lo.mp4
  • artificial_eye_lo.mp4
  • etc.

\\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

  • asset_lo.mp4
  • asset_med.mp4
  • asset_hi.mp4
  • asset.txt
  • asset.adb.xml
  • asset_med.jpg

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

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM