Header RSS Feed
If you only want to see the articles of a certain category, please click on the desired category below:
ALL Android Backup BSD Database Hacks Hardware Internet Linux Mail MySQL Monitoring Network Personal PHP Proxy Shell Solaris Unix Virtualization VMware Windows Wyse

Linux/Unix seq: Add a zero digit in front of 1-9
Monday - Oct 7th 2013 - by - (2 comments)

The Linux command seq can be very helpful for some automation tasks and loops, for example to count up IP addresses:

for i in $(seq 1 10); do echo "192.168.45.$i"; done

But as most host names are counted differently (myserver01, myserver02, etc), seq cannot be used for this purpose. Or can it?

The manpage of seq reveals an option for format (-f FORMAT, --format=FORMAT) which unfortunately doesn't really explain the format option in an understandable English.
After some trying around, I got it to work with the following syntax:

seq -f %02g 01 10

I try to explain it as I understand it: The %02g stands for use the format output %g (which is the default) but with a 0 in front of the number. The 2 stands for the minimum "character size" of the number.

Here the examples put together one after another. First the default %g format:

# %g: Default format (displays real numbers, e.g. 1,2,3,4,...,15,16,17, etc)
seq -f %g 1 5


 Now let's add the '2' in front of the default format. Notice the "space" in front of the number?

# %2g: Default format but the number must have a minimum character size of 2
seq -f %2g 1 5

Instead of a space, which is nonsense for a number, we use a zero:

# %02g: Minimum 2 characters and a zero in front (if there are less than 2 chars)
seq -f %02g 1 5


Add a comment

Show form to leave a comment

Comments (newest first):

Claudio from Switzerland wrote on Oct 8th, 2013:
Nice, Alex! Didn't know about that echo function in bash! Works nicely:

# echo {01..22..1}
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22

It also works on FreeBSD 9.2 (bash 4.2.5) and SmartOS (bash 4.1.0) but not on Solaris 11 (bash 3.2.25).

Alexander from Alberschwende wrote on Oct 7th, 2013:
Bash can do it without external tools, which might not exist on non Gnu systems like Solaris or even SmartOS...

From bash man page: When either x or y begins with a zero, the shell attempts to force all generated terms to contain the same number of digits, zero-padding where necessary.

root@Speicher ~ # echo {02..22..6}
02 08 14 20
root@Speicher ~ #

Go to Homepage home
Linux Howtos how to's
Monitoring Plugins monitoring plugins
Links links

Valid HTML 4.01 Transitional
Valid CSS!
[Valid RSS]

6937 Days
until Death of Computers