Home > bash > bash – Padding numbers in loops

bash – Padding numbers in loops

Problem:
I needed a preceeding zero before single digits to represent hours.

shell>for i in 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23; do echo $i; done;

Solution:
Use sed or printf

shell> for i in  $(seq 0 23 | sed 's/^\([0-9]\)$/0\1/'); do echo $i; done

OR

shell> for i in  $(seq 0 23 | xargs env printf "%.2d\n"); do echo $i; done

Update:(2012-06-05)
From man seq

-w, –equal-width
equalize width by padding with leading zeroes

Which now makes it

shell> for i in  $(seq -w 0 23); do echo $i; done
Advertisements
Categories: bash Tags: , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: