7

I have strings containing percent-escaped characters like %20 and %5B, and I would like to transform it to "normal" characters like \ for %20 and [ for %5B.

How can I do that?

Mechanical snail
  • 29,755
  • 14
  • 88
  • 113
Dorian
  • 22,759
  • 8
  • 120
  • 116

2 Answers2

11

The builtin printf in bash has a special format specifier (i.e. %b) which converts \x** to the corresponding value:

$ str='foo%20%5B12%5D'
$ printf "%b\n" "${str//%/\\x}"
foo [12]
marco
  • 4,455
  • 1
  • 23
  • 20
2

Finally, thanks to #bash IRC channel, I found a "not so bad" solution :

echo `echo string%20with%5Bsome%23 | sed 's/%/\\\x/g'`
Dorian
  • 22,759
  • 8
  • 120
  • 116
  • I don't see what the surrounding `echo` buys you. Does `echo string%20with%5Bsome%23 | sed 's/%/\\\x/g'` not work? – Thanatos Feb 22 '11 at 18:37
  • 1
    @Thanatos: The sed merely changes `string%20with%5Bsome%23` into `string\x20with\x5Bsome\x23`. Passing this to `echo -e` will mean that the `\x..` escapes are correctly processed. [Missing `-e` and the backticks should be wrapped in double quotes: `echo -e "$(echo string%20with%5Bsome%23 | sed 's/%/\\\x/g')"`.] – bobbogo Feb 22 '11 at 18:52
  • 1
    if you want to change from a file: `echo \`sed 's/%/\\\x/g' $file\` > $newfile` – lolesque Jun 22 '16 at 09:55