Skip to content

Instantly share code, notes, and snippets.

@bstpierre
Created August 25, 2011 14:51
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save bstpierre/1170837 to your computer and use it in GitHub Desktop.
Save bstpierre/1170837 to your computer and use it in GitHub Desktop.
Dump a (binary) file as a series of hex escape sequences
#!/bin/bash
#
#
# Dump a (binary) file as a series of hex escape sequences suitable
# for bash's builtin "echo -n -e".
#
# `od -tx1` outputs each byte as two hex digits, on multiple lines,
# with each line beginning with the offset.
# The first sed expression removes the offset info.
# The second sed expression ($d) removes the last line -- just an
# offset with no data.
# The third sed expression adds a space at the beginning of each line,
# for the next expression...
# The fourth sed expression replaces all spaces with bash's "echo -e"
# hex escape sequence, "\x".
# `tr -d` removes newlines, so that the entire sequence of hex escapes
# does not have any extra characters.
od -tx1 $1 |
sed -e 's/^[0-9]* //' -e '$d' -e 's/^/ /' -e 's/ /\\x/g' |
tr -d '\n'
# To test: send a file into this command, `echo -e` the output,
# redirecting to a new file, then compare the two files.
#
# E.g.
#
# echo -n -e $(hexecho my_test_file) > my_test_output
# diff my_test_file my_test_output
@liancheng
Copy link

Thanks for the script, it helps a lot! But there is a little bug: instead of -tx1, od should be invoked with -tx1 -v. Otherwise a * would be inserted into the output to mark the line suppression.

@ththvseo
Copy link

ththvseo commented Jul 18, 2016

you suppress the offset with od -An, better than removing it with sed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment