Batch rename files w/ leading zeros and variations in filename [closed]
I have a set of files:
foo_1_somestring.txt
foo_2_adifferentstring.txt
....
foo_124_anotherstring.txt
I want to batch rename them to:
foo_001_somestring.txt
foo_002_adifferentstring.txt
....
foo_124_anotherstring.txt
How can I do this in Windows 10 or Linux?
ETA: this question is about how to batch rename a set of files so they follow a naming convention that allows the files to be ordered numerically, ie pads the numbered files w/ an appropriate number of zeros so that they can be ordered by name without file 2 appearing before file 125.
i was unable to find another posting that addressed this problem where the file names have a portion that remains the same (the "foo_" in the beginning) and a portion that varies
Solution 1:
On Linux, assuming you want 3-digit numbers, and that the number is always between 2 underscores:
sudo apt install rename
rename 's/_([0-9]+)_/sprintf("_%03d_",$1)/e' foo*
The rename
program may already be installed. It is a simple program that takes a Perl expression and uses it to rename the given files, or foo*
in this case. The Perl expression here captures the number between parentheses and uses sprintf
to convert it to a 3-digit number. Use %04d
, above, for 4-digit numbers.
This can also work on Windows 10 using WSL.