Ergo
Ergo

Reputation: 1

Bash script for moving files and their parent directory

I have searched and a lot of topics dance around what I am trying to accomplish. I have over 2,000 m4a files buried in with 17,000 mp3s. The directory structure is /home/me/Music/MP3/Artist/Album/song.m4a. I want to use 'find' to discover the m4a songs, move them, their album directory, and their artist directory to /home/me/Music/M4A/Artist/Album/song.m4a. I have been unsuccessful with the mv -exec switch and I have been unsuccessful using basename and/or dirname to create a script. The parent and grand-parent directories have me thrown. Moving the files themselves are not a problem, just creating the directory structure AND moving the files. In a piecemeal effort, I have exported the file list find /home/me/Music/MP3 -name "*.m4a" >> dir.sh (partly because I wanted to see the file locations and # of songs). I then ran sed 's/MP3/M4A/g' dir.sh to replace the MP3 with M4A. Dropping the song.m4a as in this sample from the dir.sh will leave me with a list of Artist/Album directories to run through a while loop with mkdir: /home/me/Music/M4A/Metallica/Re-load/Metallica - The Unforgiven.m4a. Unfortunately, this is where I am stuck, dirname yields a '.'

Upvotes: 0

Views: 416

Answers (1)

ikrabbe
ikrabbe

Reputation: 1929

find /home/me/Music/MP3 -name \*.m4a| sed -e 's/.*/mkdir -p $(dirname "&"); mv "&" "&"M4A;/' | sed -e 's/MP3\([^"]*\)"M4A$/M4A\1"/' > moveit_baby.sh
bash moveit_baby.sh

should do the job, but check "moveit_baby.sh" before you call it.

Depending on your sed implementation you will need \(\) or plain () in the second sed. Of course the string "MP3" should neither be part of Artist, Album or song name, otherwise you need a more complex filter, see below.

You might further optimize when you insert mkdir -p only if the dirname changes. Such more complex decisions on input parameters are better achieved with while read loops

find /home/me/Music/MP3 -name \*.m4a | while read file
do
    # do anything you want to $file here
done

Upvotes: 1

Related Questions