Search code examples
linuxbashmediafile-renamebatch-rename

Removing specific part of filename in Linux (what's after the second dash) for all files in folder


I use the command line utility youtube-dl to download videos from youtube and make mp3s from them with avconv. I'm doing this under Ubuntu 14.04 and very happy with it.

The utility downloads the files and saves them with the following name scheme:

TITLE(artist-track)-ID.mp3

So an actual filename looks like EPIC RAP BATTLE of MANLINESS-_EzDRpkfaO4.mp3.

Some other file names in the folder look like:

EPIC RAP BATTLE of MANLINESS-_EzDRpkfaO4.mp3
Martin Garrix - Animals (Official Video)-gCYcHz2k5x0.mp3
Stromae - Papaoutai-oiKj0Z_Xnjc.mp3

At first, this was no problem. It didn't bother me while listening to my music in Rhythmbox. But when moving to phone or other devices it is pretty confusing to see a so long name, and some players, like the Samsung ones, treat that last part (id after second dash) of the name as Album or something.

So what I'd like to create is a Bash script that removes what's after the second dash in the name for all files, i.e., transform the name

‎Martin Garrix - Animals (Official Video)-gCYcHz2k5x0.mp3

to the name

Martin Garrix - Animals (Official Video).mp3.

I think it is possible to write such a Bash file to do this with some kind of loop and sed orgrep and mv.

And also, is it possible to instruct youtube-dl to exclude the ID from now on? I am currently downloading with the command

youtube-dl --extract-audio --audio-quality 0 --audio-format mp3 URL

Solution

  • Using a bash script:

    #!/bin/bash
    shopt -s extglob
    for A in *.mp3; do
       B=${A/%-+([[:alnum:]_]).mp3/.mp3}
       [[ $A != "$B" ]] && mv "$A" "$B"
    done
    

    That would fix your filenames for files that were already downloaded.