While the answer from raina77ow about the strings(1)
command is the correct way to get the result you actually wanted, the specific request to leverage hexdump(1)
to filter out only printable characters may make sense in some contexts. I'll respond to that specifically here.
The hexdump utility turns out to support a startlingly generalized formatting engine. This was probably done to make the implementation of the various selectable formats more uniform. If your copy of hexdump exposes that engine (as many do) through the -e
command line option, then you can actually have it do what you asked for.
The key is the -e
option and the formatting language it supports. That language allows the specification of format strings that consume bytes of the input and produce text. A command such as:
$ hexdump -e "16 \"%_p\" \"\\n\"" hexdump.exe | head -16
will consume 16 bytes at a time, display them via the %_p
format, and add a newline after each 16th byte. Each non-printable character is replaced with a .
in the output.
Other character-oriented formats to consider are %_c
and %_u
. The first replaces non-printing character with their ANSI-C escape sequence, or with a three digit octal number. The second replaces non-printing each character with the conventional name of the ASCII control character, or by a two-digit hexadecimal number.
If your copy of hexdump
lacks the -e
option, or is slow, or you lack an implementation of hexdump
at all, then the liberally licensed, fast, and reasonably portable implementation of hexdump
recently released by William Ahern is worth looking at. It should build for lots of Unix-like systems out of the box, and with only minor tweaks it builds with MingW GCC on Windows. A key attribute of this implementation is that the single source file can be built as a shared library for inclusion in another program, as a Lua module for use from Lua, as well as a standalone executable implementing the hexdump
command.