Bash – Convert ascii code to hexadecimal in UNIX shell script

bashshell

I'd like to convert ASCII code (like - or _ or ., etc.) to hexadecimal representation in the Unix shell (without bc command), eg : - => %2d.

Any ideas?

Best Answer

There's a printf tool that simulates the C function; normally it's at /usr/bin/printf, but a lot of shells implement built-ins for it as well. You can use %02x to get the hex representation of a character, but you need to make sure you pass a string that includes the character in single-quotes (Edit: It turns out just a single-quote at the beginning is sufficient):

printf "%%%02x\n" "'-"   # Outputs %2d

You can make a shell function for convenience:

function hex() {
    printf "%%%02x\n" "'$1"
}

hex -   # Outputs %2d
hex _   # Outputs %5f
hex .   # Outputs %2e