Re: Extracting the last field (144 Views)
Reply
Super Advisor
Henry Chua
Posts: 444
Registered: ‎09-05-2004
Message 1 of 7 (144 Views)
Accepted Solution

Extracting the last field

Hi guys,

I have a big datafile and will like to extract the last field of each line i.e. if i have a string "Field1 Field2 Field3 .." how can i extract the last field if the number of field is unknown using perl?

Best regards
Henry
Please use plain text.
Honored Contributor
Peter Godron
Posts: 4,470
Registered: ‎02-13-2002
Message 2 of 7 (144 Views)

Re: Extracting the last field

Henry,
assuming that there are no souble-spaces:

#!/usr/bin/sh
while read record
do
# Count the number of words
max=`echo "$record" | wc -w `
# Get that last field
echo "$record" | cut -d' ' -f $max
done < a.lis
Please use plain text.
Acclaimed Contributor
Dennis Handly
Posts: 24,877
Registered: ‎03-06-2006
Message 3 of 7 (144 Views)

Re: Extracting the last field

For awk you can use:
awk '{print $NF}'
Please use plain text.
Honored Contributor
Oviwan
Posts: 692
Registered: ‎11-29-2005
Message 4 of 7 (144 Views)

Re: Extracting the last field

Hey

u can use:

echo a b c | perl -lane 'print "@F[-1]"'

returns c

use instead of echo a b c, cat filename

Regards
Please use plain text.
Super Advisor
Henry Chua
Posts: 444
Registered: ‎09-05-2004
Message 5 of 7 (144 Views)

Re: Extracting the last field

Thanks Oviwan,

May I know how can i implement for a loop in a script. Example to print the last field for a file i am reading:

...
foreach $line () {
#print last field of the textfile
}
...

Thanks in advance.

Best regards
Henry
Please use plain text.
Honored Contributor
Oviwan
Posts: 692
Registered: ‎11-29-2005
Message 6 of 7 (144 Views)

Re: Extracting the last field

Try this

open(FILE,"<","filename");

while () {
@fields=split(/\ /,$_); #split spaces
print $fields[$#fields];
}

Regards
Please use plain text.
Acclaimed Contributor
James R. Ferguson
Posts: 21,184
Registered: ‎07-06-2000
Message 7 of 7 (144 Views)

Re: Extracting the last field

Hi Henry:

To print the last field of a file:

# perl -nale 'print $F[$#F]' filename

Regards!

...JRF...
Please use plain text.
The opinions expressed above are the personal opinions of the authors, not of HP. By using this site, you accept the Terms of Use and Rules of Participation