How to convert hex to ASCII characters in the Linux shell?

Krystian Cybulski picture Krystian Cybulski · Oct 22, 2009 · Viewed 118.3k times · Source

Lets say that I have a string 5a.

This is the hex representation of the ASCII letter Z.

I need to know a Linux shell command which will take a hex string and output the ASCII characters that the string represents.

So if I do:

echo 5a | command_im_looking_for

I will see a solitary letter Z:

Z

Answer

josch picture josch · Oct 7, 2011

I used to do this using xxd

echo -n 5a | xxd -r -p

But then I realised that in Debian/Ubuntu, xxd is part of vim-common and hence might not be present in a minimal system. To also avoid perl (imho also not part of a minimal system) I ended up using sed, xargs and printf like this:

echo -n 5a | sed 's/\([0-9A-F]\{2\}\)/\\\\\\x\1/gI' | xargs printf

Mostly I only want to convert a few bytes and it's okay for such tasks. The advantage of this solution over the one of ghostdog74 is, that this can convert hex strings of arbitrary lengths automatically. xargs is used because printf doesnt read from standard input.