How to create a hex dump of file containing only the hex characters without spaces in bash?

前端 未结 6 1336
后悔当初
后悔当初 2020-11-30 17:22

How do I create an unmodified hex dump of a binary file in Linux using bash? The od and hexdump commands both insert spaces in the

相关标签:
6条回答
  • 2020-11-30 17:30

    I think this is the most widely supported version (requiring only POSIX defined tr and od behavior):

    cat "$file" | od -v -t x1 -A n | tr -d ' \n'
    

    This uses od to print each byte as hex without address without skipping repeated bytes and tr to delete all spaces and linefeeds in the output. Note that not even the trailing linefeed is emitted here. (The cat is intentional to allow multicore processing where cat can wait for filesystem while od is still processing previously read part. Single core users may want replace that with < "$file" od ... to save starting one additional process.)

    0 讨论(0)
  • xxd -p file
    

    Or if you want it all on a single line:

    xxd -p file | tr -d '\n'
    
    0 讨论(0)
  • 2020-11-30 17:33

    It seems to depend on the details of the version of od. On OSX, use this:

    od -t x1 -An file |tr -d '\n '
    

    (That's print as type hex bytes, with no address. And whitespace deleted afterwards, of course.)

    0 讨论(0)
  • 2020-11-30 17:38

    The other answers are preferable, but for a pure Bash solution, I've modified the script in my answer here to be able to output a continuous stream of hex characters representing the contents of a file. (Its normal mode is to emulate hexdump -C.)

    0 讨论(0)
  • 2020-11-30 17:42

    Perl one-liner:

    perl -e 'local $/; print unpack "H*", <>' file
    
    0 讨论(0)
  • 2020-11-30 17:49

    Format strings can make hexdump behave exactly as you want it to (no whitespace at all, byte by byte):

    hexdump -ve '1/1 "%.2x"'
    

    1/1 means "each format is applied once and takes one byte", and "%.2x" is the actual format string, like in printf. In this case: 2-character hexadecimal number, leading zeros if shorter.

    0 讨论(0)
提交回复
热议问题