Command to escape a string in bash

后端 未结 3 1696
遥遥无期
遥遥无期 2020-11-30 21:14

I need a bash command that will convert a string to something that is escaped. Here\'s an example:

echo \"hello\\world\" | escape | someprog
相关标签:
3条回答
  • 2020-11-30 21:34

    In Bash:

    printf "%q" "hello\world" | someprog
    

    for example:

    printf "%q" "hello\world"
    hello\\world
    

    This could be used through variables too:

    printf -v var "%q\n" "hello\world"
    echo "$var"
    hello\\world
    
    0 讨论(0)
  • 2020-11-30 21:38

    You can use perl to replace various characters, for example:

    $ echo "Hello\ world" | perl -pe 's/\\/\\\\/g'
    Hello\\ world
    

    Depending on the nature of your escape, you can chain multiple calls to escape the proper characters.

    0 讨论(0)
  • 2020-11-30 21:46

    Pure Bash, use parameter substitution:

    string="Hello\ world"
    echo ${string//\\/\\\\} | someprog
    
    0 讨论(0)
提交回复
热议问题