Quoting special characters with sed

后端 未结 2 1441
暖寄归人
暖寄归人 2021-01-16 07:12

I\'m trying to look in a variable passed to my program (the variable is $1) and to replace any special characters with quoted forms of said special character, in order to no

2条回答
  •  清歌不尽
    2021-01-16 07:37

    The problem with what you've done is that you haven't quoted your sed expressions. For example, write

    sed s/\*/\\*/
    

    either as

    sed 's/\*/\\*/'
    

    or

    sed s/\*/\\\\*/
    

    I'm not sure why do you need that elaborate function in order to escape special characters. You could define a function that would give back the escaped input string:

    myescape() { printf "%q" "$1"; }
    

    %q

    causes printf to output the corresponding argument in a format that can be reused as shell input.

    Another function for passing arguments to sed:

    myreplace() { sed "s/$1/$2/" <<< "$3"; }
    

    Now you could invoke it by saying:

    myreplace "$(myescape 'pattern')" "replacement" "original_string"
    

    Example:

    $ myescape() { printf "%q" "$1"; }
    $ myreplace() { sed "s/$1/$2/" <<< "$3"; }
    $ myreplace $(myescape 'a\^a*') 'test' 'aa\^a*aa[aaa]a'
    atestaa[aaa]a
    

提交回复
热议问题