Viewing Output in Hex

Problem

You need to see output in hex mode to verify that a certain whitespace or unprintable character is as expected.

Solution

Pipe the output though hexdump using the -C option for canonical output:

$ hexdump -C filename
00000000  4c 69 6e 65 20 31 0a 4c 69 6e 65 20 32 0a 0a 4c |Line 1.Line 2..L|
00000010  69 6e 65 20 34 0a 4c 69 6e 65 20 35 0a 0a       |ine 4.Line 5..|
0000001e

For example, nl uses spaces (ASCII 20), then the line number, then a tab (ASCII 09) in its output:

$ nl -ba filename | hexdump -C
0000000020 20 20 20 20 31 09 4c  69 6e 65 20 31 0a 20 20 |     1.Line 1.  |
00000010  20 20 20 32 09 4c 69 6e  65 20 32 0a 20 20 20 20 |   2.Line 2.    |
00000020  20 33 09 0a 20 20 20 20  20 34 09 4c 69 6e 65 20 | 3..     4.Line |
00000030  34 0a 20 20 20 20 20 35  09 4c 69 6e 65 20 35 0a |4.     5.Line 5.|
00000040  20 20 20 20 20 36 09 0a                          |     6..|
00000048

Discussion

hexdump is a BSD utility that also comes with many Linux distributions. Other systems, notably Solaris, do not have it by default. You can use the octal dump command od, but it’s a lot harder to read:

$ nl -ba filename | od -x 0000000 2020 2020 3120 4c09 6e69 2065 0a31 2020 0000020 2020 3220 4c09 6e69 2065 0a32 2020 2020 0000040 3320 0a09 2020 2020 3420 4c09 6e69 2065 0000060 0a34 2020 2020 3520 4c09 6e69 2065 0a35 0000100 2020 2020 3620 0a09 0000110 $ nl -ba filename | od -tx1 0000000 20 20 20 20 20 31 09 4c 69 6e 65 20 31 0a 20 20 0000020 20 20 20 32 09 4c 69 6e 65 20 32 0a 20 20 20 20 0000040 20 33 09 0a 20 20 20 20 20 34 09 4c ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.