Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Refer to field headings?

7 views
Skip to first unread message

Sashi

unread,
Nov 27, 2007, 3:30:33 PM11/27/07
to
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

Ed Morton

unread,
Nov 27, 2007, 3:44:02 PM11/27/07
to

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

Regards,

Ed.

Janis Papanagnou

unread,
Nov 27, 2007, 3:49:58 PM11/27/07
to

Not so elegant, but anyway...

BEGIN { FS=","}
NR==1 { for(f=1;f<=NF;f++) m[$f]=f; next }
$m["region_name"] ~ /ASPAC/


Janis

>
> Thanks,
> Sashi

Ed Morton

unread,
Nov 27, 2007, 4:17:29 PM11/27/07
to

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.

Sashi

unread,
Nov 27, 2007, 4:54:37 PM11/27/07
to

I thought as much (of having to store the field names in an array and
referring to them).

Thanks for the help!
Sashi

0 new messages