Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell command to format numbers inside filenames

Tags:

bash

shell

I have a folder containing the following files:

trackingData-00-1.data, trackingData-00-2.data, ..., trackingData-00-2345.data

And I would like to rename them by formatting numbers with 4 digits

trackingData-00-0001.data, trackingData-00-0002.data, ..., trackingData-00-2345.data

How can I achieve that with a bash shell command?

like image 627
sdabet Avatar asked Jun 25 '26 09:06

sdabet


1 Answers

A pure bash solution:

for f in trackingData-00-*.data; do
    [[ $f =~ trackingData-00-([0-9]+).data ]]
    mv "$f" $(printf "trackingData-00-%04d.data" ${BASH_REMATCH[1]})
done

A regular expression extracts the number to pad and stores it in the BASH_REMATCH array. Then printf is used to create the new file name, with the number reinserted and padded with zeros.

like image 81
chepner Avatar answered Jun 27 '26 22:06

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!