2014年5月5日月曜日

dd コマンドでバイナリデータを編集する方法

バイナリエディタの無い環境で、バイナリファイルを編集する方法。
echo と dd の組み合わせでいけます。

サンプルとして、あらかじめ、128 byte の All 0x00 データ (hoge.dat)を作っておきます。
このファイルの作り方については、まさおのブログ (表): 任意サイズのファイルを作る 参照。
hexdump で内容確認。

$ hexdump -Cv hoge.dat
00000000  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
00000010  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
00000020  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
00000030  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
00000040  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
00000050  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
00000060  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
00000070  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
00000080

16 byte 目 (0x00000010) から 2 byte の 0x5A5A を書き込む例。
0x5A は ASCII の "Z" ですが、任意の 16 進数データを書き込むことができます。

$ echo -en '\x5A\x5A' | dd of=./hoge.dat bs=1 seek=16 conv=notrunc
2+0 records in
2+0 records out

$ hexdump -Cv hoge.dat
00000000  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
00000010  5a 5a 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |ZZ..............|
00000020  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
00000030  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
00000040  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
00000050  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
00000060  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
00000070  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
00000080

参考: http://blog.heartnet.me/2012/07/dd.html

● バイナリ, 編集, binary, edit, bvi, なし, editor, not use, dd, echo, hexdump, 修正, seek