Extract Last Field

You can use 'cut' to extract the last field of a line if you know how many fields there are, eg:
field=`cut -d: -f8 file`

But if you don't know the maximum number of fields or the number of fields per line are not consistent, awk can come to the rescue. awk has the inbuilt variable NF for the number of fields. By using this variable we can use it to extract the last field by using:

field=`awk -F: '{print $NF}'`

or you can use calculations to retrieve any field relative to the last field. For example to retrieve the second last field, use:

field=`awk -F: '{print $(NF-1)}'`

Have a Unix Problem
Do you have a UNIX Question?

Unix Books :-
UNIX Programming, Certification, System Administration, Performance Tuning Reference Books

Return to : - Unix System Administration Hints and Tips

(c) www.gotothings.com All material on this site is Copyright.
Every effort is made to ensure the content integrity.  Information used on this site is at your own risk.
All product names are trademarks of their respective companies.
The site www.gotothings.com is in no way affiliated with or endorsed by any company listed at this site.
Any unauthorised copying or mirroring is prohibited.