DEV Community

Pavol Z. Kutaj
Pavol Z. Kutaj

Posted on

How to Skip Empty Lines in Bash Using awk

The aim of this page📝 is to explain how to use awk in Bash to process specific lines of output and handle empty lines. Often I am reading/writing with Hashicorp's Consul K/V and have a cc wrapper into which I'm passing regex to give me matches of the KV tree. I'd prefer using jq and json, but consul CLI offers json format only for the export of the whole store, so I'm slowly learning awk (which is also good for in-shell ((non-python)) csv processing).

Anyways...

  • Run the command to find specific lines: cc your_company .*loader.*version.*6.
  • Sample output:
  /loader/input/version:6.1.1
  /loader/input/version:6.1.1
Enter fullscreen mode Exit fullscreen mode
  • Use awk to select specific lines.
  • Print the second and third lines:
  cc your_company .*loader.*version.*6 | awk 'NR==2 || NR==3'
Enter fullscreen mode Exit fullscreen mode
  • Skip the first empty line using awk:
  cc your_company .*loader.*version.*6 | awk 'NF > 0 { print }'
Enter fullscreen mode Exit fullscreen mode
  • Understanding awk line numbering.
  • AWK is not zero-indexed; it starts from 1.
  • NR: Number of Records. Represents the current line number.
  • NF: Number of Fields. Represents the number of fields in the current line.
  • Skip first line and process subsequent lines:
  cc your_company .*loader.*version.*6 | awk 'NR > 1'
Enter fullscreen mode Exit fullscreen mode
  • Combined condition for skipping the first line and empty lines:
  cc your_company .*loader.*version.*6 | awk 'NR > 1 && NF > 0'
Enter fullscreen mode Exit fullscreen mode

LINKS

Heroku

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

Postmark Image

"Please fix this..."

Focus on creating stellar experiences without email headaches. Postmark's reliable API and detailed analytics make your transactional emails as polished as your product.

Start free