Quick question

When I have a file like this:

0084AF aj-123-a NAME Ajay NAME Kumar Engineer
015ED6 ck-345-c
020B25 ef-456-e
027458 pq-890-p NAME Peter NAME Salob Doctor
0318F0 xy-123-x NAME Xavier Arul NAME Yesu Supervisor
0344CA de-456-d

where - The first NAME is followed by one or more names (depending on first and middle names) and the second NAME is followed by the last name and profession.

My question is:

How could I extract only the "last name" for each id (0084AF, etc) when a NAME exists? (the lines with no NAME are to be ignored.)

The confusion here is the fist NAME field that could have more than one name following it (which makes the number of fields on the output inconsistent) as you could see for the id 0318F0.

Any suggestions?

grep NAME | awk '{print $4}'
maybe :o

grep NAME | awk '{print $(NF-1)}'

This gives 2nd last field every time

Sweet, what's NF?

#!/usr/bin/perl
use strict;
open FH,"<a.txt";
while(<FH>){
	print $1,"\n" if /^.*NAME.*NAME (.*) .*$/;
	print "No NAME\n" if !/^.*NAME.*NAME (.*) .*$/;
}
close FH;

NF- Total Number of Fields in a row

thanks