top of page

How to display the last word in every line of a file in Unix

In this Blogpost we will see and learn how to display the last word in every line of a file. Well, this one is pretty easy if you know the meaning of $NF (number of fields) in awk.

Syntaxes:

awk '{print $NF}
awk -F: '{print $NF}'

NF for awk represents the number of fields (e.g., 6), so $NF then represents the value of the rightmost field (e.g., $6).

$ cat numbers
1 2 3 4 5 6
one two three four five six
$ awk '{print $NF}' numbers
6
six

This trick makes it easy for you to print the rightmost word in a file even when each line might contain a different number of words. If you want to print some other word relative to the end of each line, you can still use NF as an anchor for your field selection. In this command, we select the next to last field by using NF-1.

$ awk '{print $(NF-1)}' numbers
5
five

That's all in this post. If you liked this blog and interested in knowing more about UNIX / LINUX / AIX. Please Like, Follow, Share & Subscribe to www.ImJhaChandan.com

Comentários


jc_logo.png

Hi, thanks for stopping by!

Welcome! to my “Muse & Learn” blog.

This website will help you to learn useful queries/SQL, Tips to troubleshoot problem and their remediation, perform DB related activities etc... and don't forget to muse with us :)....

It cover few useful information on below topics :

 

MySQL, SQL Server, DB2, Linux/UNIX/AIX, HTML ....

Let the posts
come to you.

Thanks for submitting!

  • Instagram
  • Facebook
  • Twitter
© 2023 By ImJhaChandan
bottom of page