Skip to main content


[aside] This is not a cross-post. Few days ago I asked the same thing on Stack Overflow, and there were several answers, but none of them works really perfect.)

I have a folder with the following files there:

1.mp3 1.mp3.mp4 1.mp4.mp3 1.txt 2.mp3 2.mp3.mp4 2.mp4.mp3 2.txt foo.mp3 foo.mp3.mp4 foo.mp4.mp3 foo.txt foo1.mp3 foo1.mp3.mp4 foo1.mp4.mp3 foo1.txt foo2.mp3 foo2.mp3.mp4 foo2.mp4.mp3 foo2.txt

Filenames like foo.mp4.mp3 mean that originally the file was MP4 and later converted to MP3.

I need to batch rename MP3 files there, so that their numbers will be padded with leading zeros, that is, 1.mp3 should be renamed 0001.mp3, 1.mp4.mp3 to 0001.mp4.mp3, foo1.mp3 to foo001.mp3, and so on.

Here are several attempts by other people:

  • rename -n 's/(\d+)/sprintf "%03d", $1/e' *.mp3
  • rename -n 's/(\d+)\.mp3/sprintf "%03d.mp3", $1/e' *.mp3
  • rename -n 's/(\d+)(\.mp3)/sprintf("%03d", $1) . $2/e or s/(\d+)(\.mp3)/sprintf "%03d%s", $1, $2/e' *.mp3
  • rename -n 's/(\d+)(\.mp3)/sprintf "%03d%s", $1, $2/e' *.mp3
  • rename -n 's/(\d+)(?=\.mp3)/sprintf "%03d", $1/e' *.mp3
  • and my own, doesn't work either: rename -n 's/(\d)(\.[^.]+)/sprintf "%03d%s", $1, $2/e' *

Maybe there is a Perl wizard here who could help me?

submitted by /u/Impressive-West-5839
[link] [comments]