BASH: unescape string

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'}"
hello
world
foo
$ 

(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>.)


POSIX sh provides printf %b for just this purpose:

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

...will emit:

some
string
...

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"
some
string
...

Using sed

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

Using awk

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

Tags:

Bash