[awk] How to escape a single quote inside awk

I want do the following

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

But escaping single quote this way does not work

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

How to do this? Thanks for help.

This question is related to awk

The answer is


A single quote is represented using \x27

Like in

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

Source


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'

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

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