Simpler Navigation for Servers and Operating Systems - Please Update Your Bookmarks
Completed: a much simpler Servers and Operating Systems section of the Community. We combined many of the older boards, so you won't have to click through so many levels to get at the information you need. Check the consolidated boards here as many sub-forums are now single boards.
If you have bookmarked forums or discussion boards in Servers and Operating Systems, we suggest you check and update them as needed.
Languages and Scripting
cancel
Showing results for 
Search instead for 
Did you mean: 

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
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
Highlighted
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...