Search code examples
shellsedescapingbackticks

shell: Using sed in backticks


I want to escape some special chars inside a string automatically. I thought of echoing that string and pipe it through some seds. This doesn't seem to work inside of backticks. So why does

echo "foo[bar]" | sed 's/\[/\\[/g'

return

foo\[bar]

but

FOO=`echo "foo[bar]" | sed 's/\[/\\[/g'` && echo $FOO

just returns

foo[bar]

?

In contrast to sed, tr works perfectly inside of backticks:

FOO=`echo "foo[bar]" | tr '[' '-' ` && echo $FOO

returns

foo-bar]

Solution

  • You need to escape the backslashes between the backticks.

    FOO=`echo "foo[bar]" | sed 's/\\[/\\\\[/g'` && echo $FOO
    

    Alternatively, use $() (this is actually the recommended method).

    FOO=$(echo "foo[bar]" | sed 's/\[/\\[/g') && echo $FOO