Skip to content

Instantly share code, notes, and snippets.

@dstebila
Last active December 9, 2022 03:46
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save dstebila/6194f90097c43c091dd2 to your computer and use it in GitHub Desktop.
Save dstebila/6194f90097c43c091dd2 to your computer and use it in GitHub Desktop.
Shell script to convert hex file to binary, stripping out any comments
#!/bin/bash
# Read either the first argument or from stdin (http://stackoverflow.com/questions/6980090/bash-read-from-file-or-stdin)
cat "${1:-/dev/stdin}" | \
# Strip out comments starting with #
sed -E 's/#.*$//' | \
# Strip out comments starting with //
sed -E 's/\/\/.*$//' | \
# Strip out multi-line comments /* ... */
perl -0777 -pe 's{/\*.*?\*/}{}gs' | \
# Strip "0x" prefixes
perl -0777 -pe 's{\b0x(..)\b}{$1}gi' | \
# Strip out all non hexadecimal characters
sed -E 's/[^0-9a-fA-F]*//g' | \
# Convert hex to binary using xxd's reverser in plain hexdump style
xxd -r -ps
@cxw42
Copy link

cxw42 commented May 28, 2020

Thank you for this script! In order to support files containing 0x.. entries, I added one transformation between lines 10 and 11 (after the first perl):

# Strip "0x" prefixes
perl -0777 -pe 's{\b0x(..)\b}{$1}gi' | \

@dstebila
Copy link
Author

Thank you for this script! In order to support files containing 0x.. entries, I added one transformation between lines 10 and 11 (after the first perl):

# Strip "0x" prefixes
perl -0777 -pe 's{\b0x(..)\b}{$1}gi' | \

Good suggestion, I've updated it.

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