Here is what I have currently:
rename -n 's/(\d+)\.txt/sprintf "%03d", $1/e' ./*.txt
This adds leading zeros but unfortunately drops an extension:
rename(./1.txt, ./001)
rename(./2.txt, ./002)
rename(./3.txt, ./003)
I tried the following, but this didn't help:
rename -n 's/(\d+)(\.txt)/sprintf "%03d", $1/e$2' ./*.txt
rename -n 's/(\d+)(\.txt)/(sprintf "%03d", $1/e)$2' ./*.txt
How to make it work?
I believe your rename
drops the extension because you tell it to. That is, your 's/(\d+)\.txt/sprintf "%03d", $1/e'
replaces \d+\.txt
with the results of sprintf "%03d", $1
, which do not include the extension.
All you really need to do is replace the integer part of the file name with the zero-padded version. Something like
rename 's/(\d+)/sprintf "%03d", $1/e' *.txt
should do the trick.