How to escape single quotes within single quoted strings

前端 未结 23 2168
说谎
说谎 2020-11-21 06:20

Let\'s say, you have a Bash alias like:

alias rxvt=\'urxvt\'

which works fine.

However:



        
23条回答
  •  孤独总比滥情好
    2020-11-21 06:58

    I always just replace each embedded single quote with the sequence: '\'' (that is: quote backslash quote quote) which closes the string, appends an escaped single quote and reopens the string.


    I often whip up a "quotify" function in my Perl scripts to do this for me. The steps would be:

    s/'/'\\''/g    # Handle each embedded quote
    $_ = qq['$_']; # Surround result with single quotes.
    

    This pretty much takes care of all cases.

    Life gets more fun when you introduce eval into your shell-scripts. You essentially have to re-quotify everything again!

    For example, create a Perl script called quotify containing the above statements:

    #!/usr/bin/perl -pl
    s/'/'\\''/g;
    $_ = qq['$_'];
    

    then use it to generate a correctly-quoted string:

    $ quotify
    urxvt -fg '#111111' -bg '#111111'
    

    result:

    'urxvt -fg '\''#111111'\'' -bg '\''#111111'\'''
    

    which can then be copy/pasted into the alias command:

    alias rxvt='urxvt -fg '\''#111111'\'' -bg '\''#111111'\'''
    

    (If you need to insert the command into an eval, run the quotify again:

     $ quotify
     alias rxvt='urxvt -fg '\''#111111'\'' -bg '\''#111111'\'''
    

    result:

    'alias rxvt='\''urxvt -fg '\''\'\'''\''#111111'\''\'\'''\'' -bg '\''\'\'''\''#111111'\''\'\'''\'''\'''
    

    which can be copy/pasted into an eval:

    eval 'alias rxvt='\''urxvt -fg '\''\'\'''\''#111111'\''\'\'''\'' -bg '\''\'\'''\''#111111'\''\'\'''\'''\'''
    

提交回复
热议问题