Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to zero-pad numeric variables in zsh (and maybe also bash?)

In zsh, when I have to create a bunch of files with zsh, I usually do something like:

for x in $(seq 1 1000); do .....; done 

This works fine, it gives me files with names foo-1.txt .. foo-1000.txt.
However, these files do not sort nicely, so I would like to zero-pad the $x variable, thus producing names of foo-0001.txt .. foo-1000.txt.

How to do that in zsh? (and bonus question, how to do it in bash?)

like image 801
ervingsb Avatar asked Mar 15 '12 08:03

ervingsb


People also ask

How to pad zeros in unix?

The character ^ indicates beginning of a line; 0* means any number of zeroes including none. This essentially returns you the number with all 0s, if any, at the beginning removed.

What is a zero padded number?

Zero padding is a technique typically employed to make the size of the input sequence equal to a power of two. In zero padding, you add zeros to the end of the input sequence so that the total number of samples is equal to the next higher power of two.


2 Answers

For reference sake, if you do not have control over the generation of the numeric values, you can do padding with:

% value=314 % echo ${(l:10::0:)value} 0000000314 % echo $value 314 
like image 135
Francisco Avatar answered Sep 29 '22 05:09

Francisco


Use the -w flag to seq (in any shell):

$ seq -w 1 10 01 02 03 04 05 06 07 08 09 10 
like image 34
Mat Avatar answered Sep 29 '22 03:09

Mat