skip to Main Content

Consider using the following program that filters hex number in the range 0x100xa0.

echo -e "0x10n0xffn0x16n0x80n0x50" | awk '$1 >= 0x10 && $1 <= 0xa0 { print $0 }'

The program works fine, if I replace all numbers using decimal equivalents, but fails with hex numbers.

The version of awk that I’m using doesn’t support --non-decimal-data – it’s the default version that comes with Debian 10 Buster.

How can I make the comparison work with hex numbers?

2

Answers


  1. awk has strtonum function for this conversion from hex to decimal:

    echo -e "0x10n0xffn0x16n0x80n0x50" |
    awk '{n = strtonum($1)} n >= 0x10 && n <= 0xa0'
    
    0x10
    0x16
    0x80
    0x50
    

    In absence of gnu awk, you may use this perl one liner also:

    echo -e "0x10n0xffn0x16n0x80n0x50" |
    perl -lane 'print if hex($F[0]) >= 0x10 && hex($F[0]) <= 0xa0'
    
    Login or Signup to reply.
  2. one trick is doing string comparison instead. Since "a">"9", this will work

    $ echo -e "0x10n0xffn0x16n0x80n0x50" | 
      awk '$1 >= "0x10" && $1 <= "0xa0"'
    
    
    0x10
    0x16
    0x80
    0x50
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search