I am trying rename files in a directory which have a 2 digit number - i.e. any and all numbers from 10 to 99.
I want to prepend a 0 so that for example 23 becomes 023, so that files like this

ep96Clone tool.mp4

rename to this

ep096Clone tool.mp4

I am using

rename -n 's/^ep([0-9]{2})([A-Za-z]*)/ep0$1$2/' *

but for some reason it is also matching filenames containing 3 digits, so rename is returning results like

ep101Blur_tool.mp4 renamed as ep0101Blur_tool.mp4

how can I restrict the substitution so that only files with 2 digits get renamed?


Your problem is the "*" in [a-zA-Z]*, which is matching no characters. Replace it by + to match at least one alpha char.

  • that did it thanks, I cant see why exactly it worked though? – the_velour_fog Oct 27 '15 at 9:34
  • because [a-zA-Z]* can match absolutely nothing, it is as if this part of the pattern isnt even there, as there are no further rules in the pattern. So you were matching the first two digits of a 3 digit number, then nothing, and replacing them with a 0 and the 2 digits. The existing 3rd digit made the [a-zA-Z]* match with "*" meaning "none". – meuh Oct 27 '15 at 9:39
  • wow, so in other words [a-zA-Z]* is the same as .* ? because in order for the backreference to capture the third digit (which it seemed to do) the [a-zA-Z]* must have matched to the digit? – the_velour_fog Oct 27 '15 at 9:44
  • no, [a-zA-Z]* didnt match the 3rd digit. Your entire pattern matched before you got to the 3rd digit! The matcher saw the 3rd digit did NOT match a single [a-zA-Z] char, so it tried to match no chars, and of course that matches anywhere, so it accepted the pattern, backing up to in front of the 3rd digit. – meuh Oct 27 '15 at 10:32

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.