Re: Refer to field headings?





On 11/27/2007 2:44 PM, Ed Morton wrote:

On 11/27/2007 2:30 PM, Sashi wrote:

Hi all,

I have a comma delimited text file which I'm parsing with awk. The
first line consists of field names and the rest of the lines have the
values.

Is it possible in [g]awk to refer to the field names instead of
positions?

For example,
awk '( $4 ~ /ASPAC/) {do something;}' < input_file

awk '( region_name ~ /ASPAC/) {do something;}' < input_file

where region_name is the title for the fourth field.

Thanks,
Sashi


I think what you want is something like this:

awk 'NR==1 {for (i=1;i<=NF;i++) f[$i]=i; next}
$f["region_name"] ~ /ASPAC/) {do something}' input_file

An alternative would be to create explicit variables based on those names (or at
least the ones you care about) to contain the field numbers:

awk 'NR==1
for (i=1;i<=NF;i++) {
if ($i == "region_name") region_name = i
else if ($i == "some_other_field") some_other_field = i
else if ....
next
}
}
$region_name ~ /ASPAC/) {do something}' input_file

Which approach to choose (array or variables) depends on how many times you need
to reference those fields (the variables require more typing at initialisation,
but less on the references) and personal preference and whether or not you'll
ever have to loop through all the field names (if you do, use the array)...

Regards,

Ed.

.



Relevant Pages

  • Re: A future of awk.
    ... the awk way. ... I mean: pass function by reference? ... Where I'd use it is in reading database files to memory, ... Memory fault -- brain fried ...
    (comp.lang.awk)
  • Re: reading a config file
    ... awk I'd manage well enough, but as a newcomer to the C language I don't ... a reference for" instead of actually learning. ...
    (comp.lang.c)
  • Re: Refer to field headings?
    ... Sashi wrote: ... I have a comma delimited text file which I'm parsing with awk. ... first line consists of field names and the rest of the lines have the ...
    (comp.lang.awk)
  • Re: awk quries
    ... Example there is a file called data.txt consists of: ... How to go about it with awk? ... >> Is it possible to print a single record instead of all records in a file ... Prev by Date: ...
    (comp.lang.awk)
  • Re: Refer to field headings?
    ... I have a comma delimited text file which I'm parsing with awk. ... first line consists of field names and the rest of the lines have the ... Is it possible in awk to refer to the field names instead of ...
    (comp.lang.awk)