Operating System - Linux
1752810 Members
5717 Online
108789 Solutions
New Discussion юеВ

Re: Extracting the last field

 
SOLVED
Go to solution
Henry Chua
Super Advisor

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
6 REPLIES 6
Peter Godron
Honored Contributor

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
Dennis Handly
Acclaimed Contributor

Re: Extracting the last field

For awk you can use:
awk '{print $NF}'
Oviwan
Honored Contributor

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
Henry Chua
Super Advisor

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
Oviwan
Honored Contributor
Solution

Re: Extracting the last field

Try this

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

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

Regards
James R. Ferguson
Acclaimed Contributor

Re: Extracting the last field

Hi Henry:

To print the last field of a file:

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

Regards!

...JRF...