Will
Will

Reputation: 99

Find character in file name bash

I have a bunch of files whose names are in the format:

artist name - song name.mp3

I am writing a bash script that will extract the artist and song name and put the file in a directory named "artist name" and the filename would just be "song name.mp3".

How would I find the "-" so I can parse the artist and song name to their appropriate variables. Also, how would I check to see if a certain "artist name" already has a directory and then put that new file into that directory?

Upvotes: 1

Views: 1082

Answers (1)

John1024
John1024

Reputation: 113834

I believe that this does what you want:

for f in *.mp3; do artist=${f%% - *}; song=${f#* - }; mkdir -p "$artist"; mv "$f" "$artist/$song"; done

Or, if you were to write in a script:

for f in *.mp3; do 
    artist=${f%% - *}
    song=${f#* - }
    mkdir -p "$artist"
    mv "$f" "$artist/$song"
done

How it works

  • for f in *.mp3; do

    This starts a loop over every mp3 file in the current directory.

  • artist=${f%% - *}; song=${f#* - }

    This extracts the artist's name and saves it in the shell variable artist and extracts the song's name and saves it in the shell variable song.

    This uses the three characters space-dash-space as the divider between artists and song.

    ${f%% - *} is an example of suffix removal. The shell looks for the longest pattern (glob) of - * and removes it from the end of the variable f.

    ${f#* - } is an example of prefix removal. The shell looks for the shortest pattern (glob) for * - and removes it from the beginning of the variable f.

    Both suffix removal and prefix removal are documented in man bash under the heading "Parameter Expansion".

  • mkdir -p "$artist"

    This makes sure that there is a directory named for the artist.

  • mv "$f" "$artist/$song"

    This moves the mp3 file to the directory

  • done

    This signals the end of the loop.

Upvotes: 3

Related Questions