Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace percent-escaped characters in string (%20, %5B, …) with bash

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?

like image 316
Dorian Avatar asked Feb 22 '11 18:02

Dorian


People also ask

How do you escape special characters in a string in Bash?

A non-quoted backslash, \, is used as an escape character in Bash. It preserves the literal value of the next character that follows, with the exception of newline.

How do I escape a Bash string?

To escape a string for use as a command line argument in Bash, simply put a backslash in front of every non-alphanumeric character. Do not wrap the string in single quotes or double quotes.

How do you escape a character in shell script?

The escape (\) preceding a character tells the shell to interpret that character literally. With certain commands and utilities, such as echo and sed, escaping a character may have the opposite effect - it can toggle on a special meaning for that character.

How does Bash handle special characters?

Bash Character Escaping. Except within single quotes, characters with special meanings in Bash have to be escaped to preserve their literal values. In practice, this is mainly done with the escape character \ <backslash>.


1 Answers

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]
like image 130
marco Avatar answered Sep 28 '22 10:09

marco