I want the following files to be renamed removing the sequence numbers.

01 X.mp3 to X.mp3

02 Add Me In.mp3 to Add Me In.mp3

I am trying with the below rename command.

rename -v -n 's/^\d+\s*([a-z]+\.mp3)$/$1\.mp3/' *.mp3

Running this command gives me this error:

Using expression: sub { use feature ':5.18'; s/^\d+\s*([a-z]+\.mp3)$/$1\.mp3/ }
  • I tried it on my machine, didn't get the error.. but your command could be improved to rename -v -n 's/^\d+\s*//' *.mp3 to get your desired result
    – Sundeep
    Jul 24 '16 at 12:58

I don't see why that error would occur. In fact, I am reasonably certain there were more lines to the error than you show; for one thing, there's no actual error message.

However, that regular expression won't actually match either of your example files. You are using [a-z]+\.mp3 which will only match lower case letters and, since you're matching all the way to the extension, it will only match files whose name consists of only lower case letters after the numbers and space you want to remove. You could instead match [a-zA-Z] or use s///i to make the match case insensitive, but it would be a better idea to not match the rest of the word at all. You just want to remove the digits and whitespace from the beginning, so just match those:

rename -vn 's/^\d+\s+//' *mp3

Solution using Parameter Expansion

for i in *.mp3 ; do mv "$i" "${i#"${i%%[!0-9 ]*}"}" ; done
  • ${i%%[!0-9 ]*} deletes from first non-digit/non-space character till end.
  • Remaining characters are passed to ${i# which then deletes them from beginning of i variable resulting in desired file name without starting digits and space
  • 1
    Values on the right side of the # are read as patterns, so, if i may contain pattern special characters (*, ?, [) its value should be (also) quoted: "${i#"${i%%[!0-9 ]*}"}".
    – IsaaC
    Nov 22 '19 at 12:51
  • @Isaac thanks, edited the answer.. although in this case, I think it isn't required because it will delete all the special characters
    – Sundeep
    Nov 22 '19 at 13:17
  • 1
    In this particular case, yes, the ${i%%[!0-9 ]*} will remove all *?[, otoh quoting will cause no ill issue either. I believe that it is a good idea to fall into the habit of seeing ${var#" … "} used in general.
    – IsaaC
    Nov 22 '19 at 23:59

Removing the -n will make it work. -n means "Just print the result instead of changing it".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.