Rename files with file names matching regular expression

Got a directory of thousands of files with numeric ranges in the file name. Unfortunately, they don't sort well because numbers aren't padded with zeroes.

ls -1
1
2
3
4
5
6
7
8
my.file.1000.txt
my.file.1001.txt
my.file.100.txt
my.file.101.txt
my.file.10.txt
my.file.11.txt
my.file.1.txt
my.file.2.txt

I would like all numeric characters to consist of four digits. Numbers consisting of fewer than four digits should be padded with zeroes.

Here's one way to do it:

1
2
3
ls | grep -E "\.[0-9]{1}\.txt" | rename 's/file./file.000/'
ls | grep -E "\.[0-9]{2}\.txt" | rename 's/file./file.00/'
ls | grep -E "\.[0-9]{3}\.txt" | rename 's/file./file.0/'

After:

ls -1
1
2
3
4
5
6
7
8
my.file.0001.txt
my.file.0002.txt
my.file.0010.txt
my.file.0011.txt
my.file.0100.txt
my.file.0101.txt
my.file.1000.txt
my.file.1001.txt

Leave a comment

NOTE: Enclose quotes in <blockquote></blockquote>. Enclose code in <pre lang="LANG"></pre> (where LANG is one of these).