Quoting quotes in awk (really quoting quotes in sh)

Ken Turkowski ken at turtlevax.UUCP
Wed Mar 12 11:28:25 AEST 1986


In article <139 at umcp-cs.UUCP> chris at umcp-cs.UUCP (Chris Torek) writes:
>I just tried the following on a 4.3BSD beta system and it worked fine:
>
>	% awk -f /dev/stdin
>	{ printf("%d: \"%s\"\n", NR, $0); }
>	control-D hi
>	1: "hi"
>	there
>	2: "there"
>	control-D %
>
>So what is the problem with quotes?

You're right; it does work.  My problem was that I was trying to feed the
program into sh on the command line.  A permutation of it is this:

awk '{ print "quoth the raven:", "'\''" $0 "'\''", "(nevermore)" }' << EOF
what do you say?
<to quote a quote>
EOF

Which results in:
quoth the raven: 'what do you say?' (nevermore)
quoth the raven: '<to quote a quote>' (nevermore)

The problem starts because I want the enclose the entire awk program in
single quotes to avoid expansion of things like $0; additionally, I
would like to print a single quote in an awk print statement.  The
solution is outlined below:

awk '{ print "quoth the raven:", "'\''" $0 "'\''", "(nevermore)" }'
    ^				  ^  ^      ^  ^		  ^
    |		first string	  |  |2ndStr|  |   third string	  |
    +-----------------------------+  +------+  +------------------+
				    ^	      ^
				    |	      |
				escaped single quotes

One of the net readers had the good suggestion of setting a variable
to equal the single quote in a string, for greater readability:

awk 'BEGIN { Q = "'\''" }
{ print "quoth the raven:", Q $0 Q, "(nevermore)" }'

Thanks to everyone who responded!
-- 
Ken Turkowski @ CIMLINC, Menlo Park, CA
UUCP: {amd,decwrl,hplabs,seismo,spar}!turtlevax!ken
ARPA: turtlevax!ken at DECWRL.DEC.COM



More information about the Comp.unix mailing list