[bash] How to zero pad a sequence of integers in bash so that all have the same width?

I need to loop some values,

for i in $(seq $first $last)
do
    does something here
done

For $first and $last, i need it to be of fixed length 5. So if the input is 1, i need to add zeros in front such that it becomes 00001. It loops till 99999 for example, but the length has to be 5.

E.g.: 00002, 00042, 00212, 012312 and so forth.

Any idea on how i can do that?

This question is related to bash numbers padding

The answer is


I pad output with more digits (zeros) than I need then use tail to only use the number of digits I am looking for. Notice that you have to use '6' in tail to get the last five digits :)

for i in $(seq 1 10)
do
RESULT=$(echo 00000$i | tail -c 6)
echo $RESULT
done

If you want N digits, add 10^N and delete the first digit.

for (( num=100; num<=105; num++ ))
do
  echo ${num:1:3}
done

Output:

01
02
03
04
05

This will work also:

for i in {0..9}{0..9}{0..9}{0..9}
do
  echo "$i"
done

Use awk like this:

awk -v start=1 -v end=10 'BEGIN{for (i=start; i<=end; i++) printf("%05d\n", i)}'

OUTPUT:

00001
00002
00003
00004
00005
00006
00007
00008
00009
00010

Update:

As pure bash alternative you can do this to get same output:

for i in {1..10}
do
   printf "%05d\n" $i
done

This way you can avoid using an external program seq which is NOT available on all the flavors of *nix.


Other way :

zeroos="000"
echo 

for num in {99..105};do
 echo ${zeroos:${#num}:${#zeroos}}${num}
done

So simple function to convert any number would be:

function leading_zero(){

    local num=$1
    local zeroos=00000
    echo ${zeroos:${#num}:${#zeroos}}${num} 

}

If the end of sequence has maximal length of padding (for example, if you want 5 digits and command is "seq 1 10000"), than you can use "-w" flag for seq - it adds padding itself.

seq -w 1 10

produce

01
02
03
04
05
06
07
08
09
10

Easier still you can just do

for i in {00001..99999}; do
  echo $i
done

One way without using external process forking is string manipulation, in a generic case it would look like this:

#start value
CNT=1

for [whatever iterative loop, seq, cat, find...];do
   # number of 0s is at least the amount of decimals needed, simple concatenation
   TEMP="000000$CNT"
   # for example 6 digits zero padded, get the last 6 character of the string
   echo ${TEMP:(-6)}
   # increment, if the for loop doesn't provide the number directly
   TEMP=$(( TEMP + 1 ))
done

This works quite well on WSL as well, where forking is a really heavy operation. I had a 110000 files list, using printf "%06d" $NUM took over 1 minute, the solution above ran in about 1 second.


1.) Create a sequence of numbers 'seq' from 1 to 1000, and fix the width '-w' (width is determined by length of ending number, in this case 4 digits for 1000).

2.) Also, select which numbers you want using 'sed -n' (in this case, we select numbers 1-100).

3.) 'echo' out each number. Numbers are stored in the variable 'i', accessed using the '$'.

Pros: This code is pretty clean.

Cons: 'seq' isn't native to all Linux systems (as I understand)

for i in `seq -w 1 1000 | sed -n '1,100p'`; 
do 
    echo $i; 
done

If you're just after padding numbers with zeros to achieve fixed length, just add the nearest multiple of 10 eg. for 2 digits, add 10^2, then remove the first 1 before displaying output.

This solution works to pad/format single numbers of any length, or a whole sequence of numbers using a for loop.

# Padding 0s zeros:
# Pure bash without externals eg. awk, sed, seq, head, tail etc.
# works with echo, no need for printf

pad=100000      ;# 5 digit fixed

for i in {0..99999}; do ((j=pad+i))
    echo ${j#?}
done

Tested on Mac OSX 10.6.8, Bash ver 3.2.48


use printf with "%05d" e.g.

printf "%05d" 1

Very simple using printf

[jaypal:~/Temp] printf "%05d\n" 1
00001
[jaypal:~/Temp] printf "%05d\n" 2
00002

Examples related to bash

Comparing a variable with a string python not working when redirecting from bash script Zipping a file in bash fails How do I prevent Conda from activating the base environment by default? Get first line of a shell command's output Fixing a systemd service 203/EXEC failure (no such file or directory) /bin/sh: apt-get: not found VSCode Change Default Terminal Run bash command on jenkins pipeline How to check if the docker engine and a docker container are running? How to switch Python versions in Terminal?

Examples related to numbers

how to display a javascript var in html body How to label scatterplot points by name? Allow 2 decimal places in <input type="number"> Why does the html input with type "number" allow the letter 'e' to be entered in the field? Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array Input type "number" won't resize C++ - how to find the length of an integer How to Generate a random number of fixed length using JavaScript? How do you check in python whether a string contains only numbers? Turn a single number into single digits Python

Examples related to padding

Can we define min-margin and max-margin, max-padding and min-padding in css? Does bootstrap have builtin padding and margin classes? Adding space/padding to a UILabel How to adjust gutter in Bootstrap 3 grid system? Why is there an unexplainable gap between these inline-block div elements? How to increase the distance between table columns in HTML? Absolute positioning ignoring padding of parent Remove all padding and margin table HTML and CSS Style the first <td> column of a table differently Using margin / padding to space <span> from the rest of the <p>