MAPK MAPK - 1 year ago 143
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

. I want to remove all the numbers, dashes and underscores in the beginning of these files and get the result:


Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download