bashでバイナリの任意の箇所を切り出す
プログラムのデバッグの一貫としてtiffのexifをバイナリ単位で調べている。 レコードにオフセット的なメタデータの相対位置を書いてあるものが多いので、画像ファイルのこの箇所(先頭から何バイト目から何バイト分)がほしい! というシチュエーションがよくあるのでタイトルの内容ができるコマンドを探していた。
色々調べてみると、以下のコマンドでできそうだ。
- 2バイトめから3バイト分表示する
tail -c +2 | head -c 3
- tail -c +NUM:先頭からNUMバイト以降を表示
-c, --bytes=[+]NUM output the last NUM bytes; or use -c +NUM to output starting with byte NUM of each file
- head -c NUM:先頭からNUMバイト分表示
-c, --bytes=[-]NUM print the first NUM bytes of each file; with the leading '-', print all but the last NUM bytes of each file
sample
- abcdeの2バイト目から3バイト分のデータを表示する
- 結果はbcdとなる
$echo abcde |tail -c +2 | head -c 3 | hd 00000000 62 63 64 |bcd| 00000003