Forum Moderators: bakedjake

Message Too Old, No Replies

get last word

         

QldRobbo

6:20 am on Apr 7, 2005 (gmt 0)

10+ Year Member



G'day,
I need to be able to get the last word from a string, how would I do this? I'm assuming I'd use sed?

Something like (as a test)

echo "From: someone <email@email.com>" ¦ sed something or other

I need to get the <email@email.com> part, if there is any whitespace after the last word, I need to delete that too

Thanks for any help
Robbo

MattyMoose

7:09 am on Apr 7, 2005 (gmt 0)

10+ Year Member



This should work:

echo "hello my name is bob" ¦ sed 's/^.* //'

returns "bob"

QldRobbo

7:22 am on Apr 7, 2005 (gmt 0)

10+ Year Member



Thanks, that words great as long as there isn't any whitespace after the last word... which is good enough

Can you explain that though, like what 's/^.* //' means

Thanks again,

Robbo

MattyMoose

7:23 pm on Apr 7, 2005 (gmt 0)

10+ Year Member



This might actually work better for you (stumbled upon it this morning):

 echo "hello my name is  bob " ¦ awk '{print $NF}'

That will return the last word no matter how many whitesaces after it. :)

From the

man awk
page: $NF is:
NF   number of fields in the current record

From that, I believe it's actually printing the value that's in $NF (the number of fields, so the last field).

HTH!
MM