How to escape a single quote inside awk
AwkAwk Problem Overview
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.
Awk Solutions
Solution 1 - Awk
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.
Solution 2 - Awk
A single quote is represented using \x27
Like in
awk 'BEGIN {FS=" ";} {printf "\x27%s\x27 ", $1}'
Solution 3 - Awk
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'
Solution 4 - Awk
awk 'BEGIN {FS=" "} {printf "\047%s\047 ", $1}'
Solution 5 - Awk
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 convenient 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.
Solution 6 - Awk
When you are using awk in the command line, you don't have to use the BEGIN block to define the field separator (FS) you can only use -F" " like:
awk -F" " {printf "\047%s\047 ", $1}'
saves you some typing. :)