DEV Community

Pavol Z. Kutaj
Pavol Z. Kutaj

Posted on

How to Print the Last Field in Bash with awk

USECASE

The aim of this pageđź“ť is to explain how to print the last field in a line of text using bash, when the number of fields varies. I was planning to use cut but learned that I need awk at the end.

  • Tools Needed: awk, cut.
  • Goal: Print the last field of varying field count lines.
  • Why: cut is limited to fixed fields.
  • Solution: Use awk for dynamic field handling.

Steps

  1. Understanding cut: Handles fixed number of fields.
  2. Limitation: cut can't handle varying fields.
  3. Solution Overview: Use awk to overcome cut limitations.
  4. Basic awk Syntax: awk '{print $NF}'.
  5. Example: echo "one two three four" | awk '{print $NF}'.
  6. Explanation:
    • echo "one two three four": Simulates text input.
    • awk '{print $NF}': Prints last field.
  7. File Input: Handle files line by line.
  8. File Example:
   cat filename.txt | awk '{print $NF}'
Enter fullscreen mode Exit fullscreen mode
  • Explanation:
    • cat filename.txt: Reads file content.
    • awk '{print $NF}': Prints last field of each line.
  • Practical Application: Use in scripts for dynamic data processing.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

đź‘‹ Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay