Shell: using sed in backticks

I want to avoid special characters inside a string automatically. I thought about repeating this chain and blowing it through some seeds. It doesn't seem to work inside backticks. So why

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

      

return

foo\[bar]

      

but

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

      

just returns

foo[bar]

      

?

Unlike sed, tr works great inside backticks:

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

      

returns

foo-bar]

      

+2


source to share


3 answers


You need to avoid backslashes between backslashes.

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

      



Alternatively use $()

(this is really the recommended method).

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

      

+6


source


How can I not use backlinks but use $ ()?

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

      



if you insist on using reverse steps i think you need to additionally rip out all \ into double \

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

      

+15


source


This is usually a case of underexposure

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

      

+2


source







All Articles