How to escape a single quote inside awk

Awk

Awk 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}'

Source

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. :)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1096734View Question on Stackoverflow
Solution 1 - AwkSteveView Answer on Stackoverflow
Solution 2 - AwktiagojcoView Answer on Stackoverflow
Solution 3 - Awkmklement0View Answer on Stackoverflow
Solution 4 - AwkSergio KView Answer on Stackoverflow
Solution 5 - Awkuser1708042View Answer on Stackoverflow
Solution 6 - AwkJeronimo RoblesView Answer on Stackoverflow