Skip to content
Advertisement

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?

Advertisement

Answer

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

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

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

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

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement