1834149 Members
2384 Online
110064 Solutions
New Discussion

Awk functionality

 
SOLVED
Go to solution
Dave Walley
Frequent Advisor

Awk functionality

Hi.

I am trying to build a line from a file using awk and I am having a problem with inserting ' into the line as the ' charatcter is used to delimit the awk function. For example

cat file|awk '{print "hi dave \'" $1}'
su: Syntax error: `"' is not matched.

my output should be
hi dave ' walley

Can anybody tell me how to include the single quote in the output.

Thanking you

Dave
why do i do this to myself
4 REPLIES 4
A. Clay Stephenson
Acclaimed Contributor

Re: Awk functionality

Hi Dave,

Your problem is not the single quote in awk but rather the single in the surrounding shell quote. On easy way around this is to build an awk script 'on the fly' using the 'here doc' convention. This also allows you to build up more than simple one-liners.

The script build your awk file and writes it to a temp file, executes awk, and then removes the temp file. Being an old C programmer i also swapped your print to a printf - it's more powerful.

Something like this:

#!/usr/bin/sh

TDIR=${TMPDIR:-/var/tmp}
PID=${$}
A1=${TDIR}/X${PID}_1.awk

cat << !EOF! > $A1
{
printf("Hi Dave ' %s\n",\$1)
}
!EOF!

cat myfile | awk -f ${A1}
STAT=$?
rm -f $A1
exit $STAT

If my typing is correct, that should do it. Note that within the 'here docs' section the '$' has to be escaped with '\'.

Regards, Clay
If it ain't broke, I can fix that.
Dave Walley
Frequent Advisor

Re: Awk functionality

Clay.

I have tried your suggestion and received absolutely nothing.

By running the myfile line I get

syntax error The source line is 5.
The error context is
!EOF! >>>
<<<



dave
why do i do this to myself
Laurent Paumier
Trusted Contributor
Solution

Re: Awk functionality

Or you could type your command like this :

cat file | awk '{print "hi dave '\''" $1}'

close the quote,
insert an escaped quote,
reopen the quote
A. Clay Stephenson
Acclaimed Contributor

Re: Awk functionality

Hi Dave,

My typing was ok but apparently the browser doesn't do a perfect job of copy/paste. When I copied in my own example, it didn't work. The problem was extra whitespace after !EOF! at the end of the here docs section. Remove the extra spaces at the end of the line and all should be well. And again, I deliberately made this more complex than a one-liner in case your script gets more complicated.

Regards, Clay
If it ain't broke, I can fix that.