2

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

2
  • Please note that superuser.com is not a free script/code writing service. If you tell us what you have tried so far (include the scripts/code you are already using) and where you are stuck then we can try to help with specific problems. You should also read How to Ask.
    – DavidPostill
    Sep 3, 2021 at 7:27
  • Apologies for the inappropriate post. I'll be reading that.
    – Rob
    Sep 3, 2021 at 22:24

1 Answer 1

3

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.

1
  • I wanted to do exactly this for a folder of files namee img1 through img600. I replaced the first underscore with the letter 'g' and it worked perfectly. I got two leading zeros for the first 10 images, one leading zero for the next 90 images, and the other image files remained as they were: rename 's/g([0-9]+)/sprintf("g%03d",$1)/e' *.png
    – Chef Tech
    Jun 20 at 14:14

Not the answer you're looking for? Browse other questions tagged .