Aso Strife
Aso Strife

Reputation: 1129

Keep zero after Hexdecimal conversion in bash

I'm writing a very simple script in bash:

for i in {000..1024} ; do 
     echo $i ; 
     echo "obase=16; $i" | bc
done

I want to print all numbers with minimum three digits as 000, 001, 002 .. until 099. With integer numbers it works good, but after obase = 16; $ i '| bcs number return with one or two digits.

How can I solve it in the easiest way?

Upvotes: 0

Views: 66

Answers (2)

Gábor Héja
Gábor Héja

Reputation: 495

You might want to use printf to format the number, for example:

for i in {0..1024} ; do 
     echo $i
     printf '%03X\n' $i
done

Or j=$(printf '%03X' $i) and then echo $j.

For more on formatting check the Format strings subsection of Syntax section here.

Upvotes: 3

William Pursell
William Pursell

Reputation: 212268

Not sure it's "easiest", but generally printf is good for formatting issues. eg

printf "%03s\n" "$(echo "obase=16; $i" | bc)"

Upvotes: 1

Related Questions