Stop manually counting columns when awk can just grab what you need
Text Processing (Grep/Sed/Awk)
Stop manually counting columns when awk can just grab what you need
🧩 The Challenge
You know that feeling when you’re staring at a massive, unformatted `ls -l` or a custom output dump and you find yourself counting spaces with your finger on the screen? I’ve wasted way too much of my life doing that, only to realize I miscounted the UID column and grepped the wrong data.
💡 The Fix
Instead of playing the counting game, you can just tell awk to print the last field or specific columns based on their content rather than their position. It saves you from the inevitable off-by-one error when the directory structure changes.
ls -l | awk '{print $(NF-1), $NF}'
⚙️ Why It Works
Using $(NF-1) is a total lifesaver because NF is a built-in variable that always holds the total number of fields in the current line, so you’re always grabbing the second-to-last column regardless of how many columns are ahead of it.
🚀 Pro-Tip: Pipe your output into column -t if it’s still hard to read, it’ll snap everything into a nice, clean table instantly.
Linux Tips & Tricks | © ngelinux.com | 10/3/2026
