MAPK MAPK - 5 months ago 20
Linux Question

How to delete numbers, dashes and underscores in the beginning of a file name

I have thousands of mp3 files but all with unusual file names such as

1-2songone.mp3
,
2songtwo.mp3
,
2_2_3_songthree.mp3
. I want to remove all the numbers, dashes and underscores in the beginning of these files and get the result:

songone.mp3
songtwo.mp3
songthree.mp3

Answer

This can be done using extended globbing:

$ ls
1-2songone.mp3  2_2_3_songthree.mp3  2songtwo.mp3
$ shopt -s extglob
$ for fname in *.mp3; do mv "$fname" "${fname##*([-_[:digit:]])}"; done
$ ls
songone.mp3  songthree.mp3  songtwo.mp3

This uses parameter expansion: ${fname##pattern} removes the longest possible match from the beginning of fname. As the pattern, we use *([-_[:digit:]]), where *(pattern) stands for "zero or more matches of pattern", and the actual pattern is a bracket expression for hyhpens, underscores and digits.

The *() expression requires the extglob shell option.