[go: up one dir, main page]

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

Top comments (0)