Sign up ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Is it possible to set the variable portion of the file name output to be a specific length and fill the extra spaces with zeros.

I want things to be ordered for other users, so I would like

curl[1-12]/file_name[1-50].kmz -o file_name-#1-#2.kmz' 

to look like

file_name-01-01.kmz or file_name-12-50.kmz

rather than

file_name-1-1.kmz and file_name-12-50.kmz

share|improve this question

2 Answers 2

up vote 2 down vote accepted

Just pad the format with leading zeros. So for your example do:

curl[01-12]/file_name[01-50].kmz -o file_name-#1-#2.kmz' 
share|improve this answer
How is this an accepted answer? Padding with zeros will fetch an incorrect URL. Also, a quote is missing from this string. – Markus Amalthea Magnuson Aug 26 at 8:58

There are many ways. You could use Bash brace expansion in a clever way to generate zero-padded filenames, but it will soon become complex. Easier is to batch rename after you have downloaded the files, using e.g. the prename script, which is available in at least Debian based distributions after installation of Perl.

This prename command will do zero padding to three digits (change the {3} to another number to change the zero padding. Make sure there are >{n-1} zeros after the second slash in the first expression):

$ ls
file_name-1-1.kmz  file_name-12-112.kmz  file_name-12-50.kmz  file_name-140-88.kmz
$ prename -v 's/([0-9]+)/00$1/g; s/0+([0-9]{3})/$1/g' *
file_name-1-1.kmz renamed as file_name-001-001.kmz
file_name-12-112.kmz renamed as file_name-012-112.kmz
file_name-12-50.kmz renamed as file_name-012-050.kmz
file_name-140-88.kmz renamed as file_name-140-088.kmz

Run as prename -nthe first time to be able to visually inspect the renames without doing any changes. Check man prename.

The rename expression works by first padding all numbers with n-1 zeros, then removing as many zeroes as is needed to have n digits left in all numbers. It will not truncate information, which is nice.

Float numbers are not handled above (e.g. file_name-12.7-112.97.kmz), but can be easily done with

s/([^\.0-9])([0-9]+)/${1}00$2/g; s/0+([0-9]{3})/$1/g

but that more general version is also more indecipherable :-) (and might have its own share of bugs; if floats are not needed, use the earlier version).

(prename is actually linked as rename on most systems.)

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.