How to escape a single quote inside awk

前端 未结 5 645
攒了一身酷
攒了一身酷 2020-11-28 20:11

I want do the following

awk \'BEGIN {FS=\" \";} {printf \"\'%s\' \", $1}\'

But escaping single quote this way does not work



        
相关标签:
5条回答
  • 2020-11-28 20:32

    For small scripts an optional way to make it readable is to use a variable like this:

    awk -v fmt="'%s'\n" '{printf fmt, $1}'
    

    I found it conveninet in a case where I had to produce many times the single-quote character in the output and the \047 were making it totally unreadable

    0 讨论(0)
  • 2020-11-28 20:38

    This maybe what you're looking for:

    awk 'BEGIN {FS=" ";} {printf "'\''%s'\'' ", $1}'
    

    That is, with '\'' you close the opening ', then print a literal ' by escaping it and finally open the ' again.

    0 讨论(0)
  • 2020-11-28 20:38

    A single quote is represented using \x27

    Like in

    awk 'BEGIN {FS=" ";} {printf "\x27%s\x27 ", $1}'
    

    Source

    0 讨论(0)
  • 2020-11-28 20:49
    awk 'BEGIN {FS=" "} {printf "\047%s\047 ", $1}'
    
    0 讨论(0)
  • 2020-11-28 20:52

    Another option is to pass the single quote as an awk variable:

    awk -v q=\' 'BEGIN {FS=" ";} {printf "%s%s%s ", q, $1, q}'
    

    Simpler example with string concatenation:

    # Prints 'test me', *including* the single quotes.
    $ awk -v q=\' '{print q $0 q }' <<<'test me'
    'test me'
    
    0 讨论(0)
提交回复
热议问题