Languages and Scripting
Showing results for 
Search instead for 
Do you mean 

Extracting the last field

SOLVED
Go to Solution
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
Highlighted
Honored Contributor [Founder]

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
Acclaimed Contributor [Founder]

Re: Extracting the last field

For awk you can use:
awk '{print $NF}'
Honored Contributor [Founder]

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
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
Honored Contributor [Founder]

Re: Extracting the last field

Try this

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

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

Regards
Acclaimed Contributor [Founder]

Re: Extracting the last field

Hi Henry:

To print the last field of a file:

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

Regards!

...JRF...