Breakbinarydataintolinesinabashone-liner?
Is there any bash one-liner that would allow me to break binary data coming from a pipe into lines?
As an example:
$ echo -ne 'x31x00x32rnx33x34x35x00rn' | xxd
This results in:
00000000: 3100 320d 0a33 3435 000d 0a 1.2..345...
And I would like to have:
00000000: 3100 320d 0a 1.2..
00000005: 3334 3500 0d0a 345...
In case the binary data contains a new line, I don't mind the message will be split in two or more lines (this will rarely happen in my case).
I have many devices in the field and having to send scripts or programs to do this would be cumbersome. The messages have variable size so xxd -c would just work for some messages.
我尝试将消息通过管道传输到read,这正确地将消息分成几行。但是由于某种原因(可能是 bash 本身),我的消息中删除了零:
echo -ne 'x31x00x32rnx33x34x35x00rn' | while read; do echo "$REPLY" | xxd; done
00000000: 3132 0d0a 12..
00000000: 3334 350d 0a 345..
(编辑:字节偏移量可以全部为零,这不是问题。最后一个示例中的问题是数据部分中缺少零。)
也许有一种方法可以在使用时保持零read?或者我的用例太麻烦了?
回答
你可以得到你想要的 90%:
$ printf 'x31x00x32rnx33x34x35x00rn' |
perl -nE 'printf "%08d: ", $c; say unpack("H*", "$_") ; $c += length'
00000000: 3100320d0a
00000005: 333435000d0a
THE END
二维码