Bye Bye Moore

PoCソルジャーな零細事業主が作業メモを残すブログ

awkで16進数をよろしく使う"non-decimal-data"オプション

実際のところ

以下は
"GNU Awk 4.1.4, API: 1.1 (GNU MPFR 4.0.1, GNU MP 6.1.2)"
での実行例です。
OSのデフォルトのawkでは対応してなかったりするので注意。

なんもないと

$ echo 0xdeadbeef | awk '{print $1 "\n ~> " $1+0}'
0xdeadbeef
 ~> 0

ですが、これに"--non-decimal-data"、あるいはその短縮形である"-n"をつけると

$ echo 0xdeadbeef | awk --non-decimal-data '{print $1 "\n ~> " $1+0}'
0xdeadbeef
 ~> 3735928559

$ echo 0xdeadbeef | awk -n '{print $1 "\n ~> " $1+0}'
0xdeadbeef
 ~> 3735928559

なお、上記の例ではPOSIX準拠でも対応するようです。

$ echo 0xdeadbeef | awk -P '{print $1 "\n ~> " $1+0}'
0xdeadbeef
 ~> 3735928559

だだ、計算するとなると--non-decimal-dataオプションが必要

$ echo 0xaa | awk -n '{print $1 "+0x02\n ~> " $1 + 0x02}'
0xaa+0x02
 ~> 172

$ echo 0xaa | awk -P '{print $1 "+0x02\n ~> " $1 + 0x02}'
0xaa+0x02
 ~> 170

将来廃止予定……??

と、それなりに使えそうなオプションですが以下のような警告が公式からでています。

CAUTION: Use of this option is not recommended. It can break old programs very badly. Instead, use the strtonum() function to convert your data (see section String-Manipulation Functions). This makes your programs easier to write and easier to read, and leads to less surprising results.

This option may disappear in a future version of gawk.