BASH: unescape string BASH: unescape string bash bash

BASH: unescape string


POSIX sh provides printf %b for just this purpose:

s='some\nstring\n...'printf '%b\n' "$s"

...will emit:

somestring...

More to the point, the APPLICATION USAGE section of the POSIX spec for echo explicitly suggests using printf %b for this purpose rather than relying on optional XSI extensions.


As you observed, echo does not solve the problem:

$ s="some\nstring\n..."$ echo "$s"some\nstring\n...

You haven't mentioned where you got that string or which escapes are in it.

Using a POSIX-compliant shell's printf

If the escapes are ones supported by printf, then try:

$ printf '%b\n' "$s"somestring...

Using sed

$ echo "$s" | sed 's/\\n/\n/g'somestring...

Using awk

$ echo "$s" | awk '{gsub(/\\n/, "\n")} 1'somestring...


If you have the string in a variable (say myvar), you can use:

${myvar//\\n/$'\n'}

For example:

$ myvar='hello\nworld\nfoo'$ echo "${myvar//\\n/$'\n'}"helloworldfoo$ 

(Note: it's usually safer to use printf %s <string> than echo <string>, if you don't have full control over the contents of <string>.)