用 bash 替换字符串 (%20, %5B, ...) 中的百分比转义字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5082149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replace percent-escaped characters in string (%20, %5B, …) with bash
提问by Dorian
I have strings containing percent-escaped characters like %20and %5B, and I would like to transform it to "normal" characters like \for %20and [for %5B.
我有包含像%20and这样的百分比转义字符的字符串%5B,我想将它转换为“正常”字符,例如\for%20和[for %5B。
How can I do that?
我怎样才能做到这一点?
回答by marco
The builtin printf in bash has a special format specifier (i.e. %b) which converts \x** to the corresponding value:
bash 中的内置 printf 有一个特殊的格式说明符(即 %b),它将 \x** 转换为相应的值:
$ str='foo%20%5B12%5D'
$ printf "%b\n" "${str//%/\x}"
foo [12]
回答by Dorian
Finally, thanks to #bash IRC channel, I found a "not so bad" solution :
最后,感谢#bash IRC 频道,我找到了一个“还不错”的解决方案:
echo `echo string%20with%5Bsome%23 | sed 's/%/\\x/g'`

