File Parsing Help

Hello,

I have a file which contains groups of fields. These groups are separated by a blank line, to form a logical record.

Each line consists of a field-value pair.

If want to find all records where field 'd' has a value of '4' and if it does, I want the value of field 'a' (from the same record).

Here's an example input file:

I want to end up with a file containing:

Import things to nore about the input file are a) the number of records varies, b) not all records contain a 'd' field, c) not all records contain a 'a' field, e) fields can be in any order within a record.

I think the answer will be to use AWK but I have very little knowledge of AWK and have only used it for very basic things.

The OS is Sun 5.8 by the way.

Help would be greatly appreciated.

Thanks.

Based on the input you supplied, the output should be:

1
9
3
6

This script will give you that:

awk '
/a/ { a = $2 }
/d/ { d = $2 }
/^$/ && d == 4 && a > 0 {
   print a 
   a = -1
   d = -1
}
END {
   if ( d == 4 && a > 0 ) print a
}
' "$FILE"

Seems to be a big gap between your requirements and the output you expect. Based on what you have stated the output should look like cfajohnson's awk script...correct???

Sorry, you are correct, the output should have read:

 
1
9
3
6

Many thanks for your help cfajohnson.

With Perl:

perl -00 -ne'print $1,"\n"if/d 4/&&/a (.)/' filename

And another AWK approach:

awk '/d 4/ && /a / {
  for (i=1; i<=NF; i++)
    if ($i == "a") print $(i+1)
	}' RS= filename