Bye Bye Moore

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

非POSIX環境のAWKでバイナリデータを弄り回したい場合、BINMODEオプションが使える

POSIX環境の場合、改行ルールが違ったりパスの記法が異なったりで若干使い勝手が変わるケースがあります。
こういう場合、gawkやmawk、cygwinawkに実装されているBINMODEオプションを使うと挙動をPOSIX準拠にすることができます。

If BINMODE is `"r"', or (BINMODE & 1) is nonzero, then binary mode is set on read (i.e., no translations on reads).
If BINMODE is "w", or (BINMODE & 2) is nonzero, then binary mode is set on write (i.e., no translations on writes).
If BINMODE is "rw" or "wr", binary mode is set for both read and write (same as (BINMODE & 3)).

実際のところ

ちょっと意味が弱いですが、BINMODEをrwに設定して、16進数で表示させる例は以下の通りです。

$ printf "abcdef\r\n" | awk -v BINMODE=rw '{print}' | od -Ad -c -toC
0000000   a   b   c   d   e   f  \r  \n
        141 142 143 144 145 146 015 012