moadeep
moadeep

Reputation: 4098

Linux/awk convert file containing decimal to hex

I have a text file containing lots of RGB colour codes in decimal. For example

000,000,000
000,003,025
000,007,048
000,010,069
000,014,089
000,017,108
000,020,125
000,024,140
000,027,155

I would like to convert each line to hex format (desired output):

00,00,00
00,03,15
00,07,30
00,08,45

I know I can use printf "%.2x,%.2x,%.2x\n" 000 010 69 however printf "%.2x,%.2x,%.2x\n" 000 010 069 does not work as 069 is not convertable.

I thought awk would be a reasonable tool for the job, but I guess I would face the same problems converting decimals such as 069 etc.

perl -le '$hex = sprintf("%.2x,%.2x,%.2x",005,69,255); print $hex' also has the same issue with 069

Upvotes: 3

Views: 7439

Answers (3)

choroba
choroba

Reputation: 241828

Perl solution:

perl -pe 's/([0-9]+)/sprintf "%02x", $1/ge' INPUT

You do not have to care about octal interpretation. It applies to literals only, not to values of variables.

Upvotes: 1

William Pursell
William Pursell

Reputation: 212238

It works fine in awk:

$ echo 000,062,102 | awk '{printf( "%x,%x,%x\n", $1,$2,$3)}' FS=,
0,3e,66

Upvotes: 8

DarkDust
DarkDust

Reputation: 92336

You're simply missing the commas between the arguments:

echo "000,010,069" | awk -F ',' '{ printf "%02X,%02X,%02X\n", $1, $2, $3 }'

produces:

00,0A,45

Verified both on Mac OS X (BSD awk) and Linux (GNU awk).

Upvotes: 5

Related Questions