Re: awk problem
- From: Ed Morton <morton@xxxxxxxxxxxxxx>
- Date: Thu, 14 Sep 2006 10:10:41 -0500
Robert Dow wrote:
I'm not very familiar with awk, and am having difficulty with the following
problem (and perhaps awk isn't even the right tool...)
I have a set of records in a file of the general form:
"Course Code","Course Name","Course Status","School Code","School Name","Course Approval Status"
For example a record might be:
"0060T0","Transfer To New Credit Arrangements","Closed","SU819","The Moray House School of Education","Closed (Postgraduate)"
I am processing these and another set of records using a shell script.
What I want to be able to do is set a variable CNAME to the second field
of the record exactly matching a given Course Code.
I tried this in my shell script ($HOME/admin/course.codes is the name of the
file containing the records).
#/bin/sh
COURSEREQ=\"$1
CNAME=`awk -F'","' '{if ($1=="$COURSEREQ") print $2;}' $HOME/admin/course.codes`
However CNAME is never set.
awk is not shell. Just like you can't use shell variables in your C programs, you can't use shell variables in your awk programs. See question 24 in the comp.unix.shell FAQ, http://home.comcast.net/~j.p.h/cus-faq-2.html#24, for how to pass the value of shell variables to awk scripts.
The perhaps peculiar line COURSEREQ=\"$1 adds
a double quote to the first argument of the shell script in order to allow
it to match what awk returns as the first field given the separator ","
It should be noted that an exact match for the course code is required, as
there are course codes such as CH0005, PH0005 and H0005 which all would match a
patter match for H0005, for example.
Any help would be appreciated.
Robert
Look:
$ cat file
"0060T0","Transfer To New Credit Arrangements","Closed","SU819","The Moray House School of Education","Closed (Postgraduate)"
$ gawk -F'\"(,\")?' '{for (i=2;i<NF;i++) print $i}' file
0060T0
Transfer To New Credit Arrangements
Closed
SU819
The Moray House School of Education
Closed (Postgraduate)
The above will work as long as you don't have escaped quotes within your fields. So, to get what you want would be:
CNAME=`gawk -v coursereq="$1" -F'\"(,\")?' '$2==coursereq{print $3}' $HOME/admin/course.codes`
Note that "coursereq" is an awk variable, not a shell variable.
<OT>
By the way, by convention only use all-upper-case names for exported shell variables.
</OT>
Regards,
Ed.
.
- Follow-Ups:
- Re: awk problem
- From: Jon LaBadie
- Re: awk problem
- References:
- awk problem
- From: Robert Dow
- awk problem
- Prev by Date: Re: Awk filer in / out
- Next by Date: Re: Split a file into repeating record groups (with filename = part of header)
- Previous by thread: awk problem
- Next by thread: Re: awk problem
- Index(es):
Relevant Pages
|