top of page

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

  • Writer: Jha Chandan
    Jha Chandan
  • Aug 25, 2021
  • 1 min read

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

Comments


jc_logo.png

Hi, thanks for stopping by!

Welcome to my “Muse & Learn” blog!
Muse a little, learn a lot.✌️

 

Here you’ll find practical SQL queries, troubleshooting tips with fixes, and step-by-step guidance for common database activities. And of course, don’t forget to pause and muse with us along the way. 🙂
 

I share insights on:​​

  • Db2

  • MySQL

  • SQL Server

  • Linux/UNIX/AIX

  • HTML …and more to come!
     

Whether you’re just starting out or looking to sharpen your DBA skills, there’s something here for you.

Let the posts
come to you.

Thanks for submitting!

  • Instagram
  • Facebook
  • X
2020-2025 © TechWithJC

Subscribe to Our Newsletter

Thanks for submitting!

  • Facebook
  • Instagram
  • X

2020-2025 © TechWithJC

bottom of page