Pavol Z. Kutaj
Posted on November 13, 2024
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
- Use
awk
to select specific lines. - Print the second and third lines:
cc your_company .*loader.*version.*6 | awk 'NR==2 || NR==3'
- Skip the first empty line using
awk
:
cc your_company .*loader.*version.*6 | awk 'NF > 0 { print }'
- 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'
- Combined condition for skipping the first line and empty lines:
cc your_company .*loader.*version.*6 | awk 'NR > 1 && NF > 0'
LINKS
đź’– đź’Ş đź™… đźš©
Pavol Z. Kutaj
Posted on November 13, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.