2

I have a script which process some information coming from a web page. I guess that because of the encoding of the page, some special characters are encoded in hexadecimal. For example, I have the the string "%2f" that should be translated to "/".

How can I, in bash, translate those special characters in hex to ASCII? Any ideas?

Anthon
  • 79,293

2 Answers2

5

Bash has a printf builtin, which can around the same as we could learn in C. The syntax a little bit differs.

printf '\x2f'

If you don't need to worry about higher-level data consistency problems, you can simply convert an url by this function:

function deUrl() {
    printf "${1//%/\\x}"
}

(It converts every % to a \x, then prints it with printf.)

peterh
  • 9,731
4

Such entities can be decoded with this python one-liner:

$ python -c "import urllib, sys; print urllib.unquote(sys.argv[1])"  "%2f"
/

The code is not limited to single characters. It will accept more complex strings:

$ python -c "import urllib, sys; print urllib.unquote(sys.argv[1])"  "%2d and %2f"
- and /

Python's urllib.unquote is documented here.

John1024
  • 74,655