shell: Using sed in backticks

前端 未结 3 685
甜味超标
甜味超标 2021-01-06 14:00

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 backt

相关标签:
3条回答
  • 2021-01-06 14:25

    How about not using backticks but use $() ?

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

    if you insist on using backticks, I think you need to extra escape all \ into double \

    FOO=`echo "foo[bar]" | sed 's/\\[/\\\\[/g'` && echo $FOO
    
    0 讨论(0)
  • 2021-01-06 14:28

    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
    
    0 讨论(0)
  • 2021-01-06 14:37

    Usually, it's a case of underescaping

    FOO=`echo "foo[bar]" | sed 's/\[/\\\[/g'` && echo $FOO
    
    0 讨论(0)
提交回复
热议问题