Re: Refer to field headings?
- From: Ed Morton <morton@xxxxxxxxxxxxxx>
- Date: Tue, 27 Nov 2007 15:17:29 -0600
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.
.
- Follow-Ups:
- Re: Refer to field headings?
- From: Sashi
- Re: Refer to field headings?
- References:
- Refer to field headings?
- From: Sashi
- Re: Refer to field headings?
- From: Ed Morton
- Refer to field headings?
- Prev by Date: Re: awk question
- Next by Date: Re: awk question
- Previous by thread: Re: Refer to field headings?
- Next by thread: Re: Refer to field headings?
- Index(es):
Relevant Pages
|