Patching Binary Files in Bash
Just the other day I ran into a particularly annoying issue: after an application upgrade, all printed documents had “<<bbj>>~D” on the first line. The application sends EPS files to the CUPS print server. For whatever reason, the files were malformed. I had neither time nor desire to look for the root cause, so I came up with a simple workaround.
The basic idea is to convert the binary file to hex, remove whatever is messing up the format, and then convert it back to binary. Here’s an example of doing this on a Solaris 11 box:
/opt/csw/bin/xxd -p "${tmpfile}" | sed 's/3c3c62626a3e3e84//g' | /opt/csw/bin/xxd -r -p > "${outfile}"
The “${tmpfile}” is the original broken EPS file; the “sed” replacement string is the hex equivalent of the offending “<<bbj>>~D” characters; and the “${outfile}” is the name of the patched EPS file that would be sent to CUPS for printing.
It took a few minutes to write a script that would intercept the application print jobs, fix the files and re-submit for printing. I’d much rather have the developers fix whatever’s causing the problem, but this would have to do for now.