command line curl - file naming example.com/[1-10].txt => 01.txt through 10.txt

2

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 http://example.com/[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

TST

Posted 2012-03-26T07:37:14.990

Reputation: 23

Answers

2

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

curl http://example.com/[01-12]/file_name[01-50].kmz -o file_name-#1-#2.kmz' 

Pathim

Posted 2012-03-26T07:37:14.990

Reputation: 36

1How is this an accepted answer? Padding with zeros will fetch an incorrect URL. Also, a quote is missing from this string. – Markus Amalthea Magnuson – 2015-08-26T08:58:41.250

0

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.)

Daniel Andersson

Posted 2012-03-26T07:37:14.990

Reputation: 20 465