Search code examples
bashshellglob

Matching whitespace in bash


I want to delete duplicate files made by itunes, which all end in " 1.mp3". I've come close to matching but I don't know how to match the space. Can somebody writeup a command to recursively delete those files from the current directory?


Solution

  • You want to go through your iTunes collection and remove Nickelback's If I care 1.mp3 but, only if the Nickelback original MP3, If I care.mp3, still exist. Right?

    Hey, your musical tastes are up to you...

    This should do the trick:

    find -name "* 1.mp3" | while read file
    do
       if [ -e "${file% 1.mp3}.mp3" ]
       then
           rm $file
       fi
    done
    

    I am finding all the duplicates (songs that end in space-1.mp3) and piping them to the while statement.

    The ${word%filter} syntax says take the $word and remove from the right hand side the glob expression filter. Thus, ${file% 1.mp3} is the name of the file sans the 1.mp3 suffix. Now, If I care 1.mp3 becomes If I care. We, therefore need to add the .mp3 suffix back on. Thus ${file% 1.mp3}.mp3. This gives us the original name of the file.

    Now, we use -e test to check if that file exists. If it does, we can delete the space-1.mp3 version of the song.

    I ran some basic tests, but I suggest you try it out first (maybe change rm $file to echo Removing file $file first and verifying that those files do have the original).