Home > Blockchain >  if condition in awk command is not working as expected in BEGIN block. correct me if am wrong
if condition in awk command is not working as expected in BEGIN block. correct me if am wrong

Time:02-17

I have a command like below

kubectl get pods |
grep -v 1/1 |
grep -v 2/2 |
awk '{print $1:$2:$3}' |
awk 'BEGIN{ print "<style>table,th,td {border:1px solid black;}

Sample output from kubectl:

NAMESPACE   NAME      READY       STATUS              RESTARTS
ABC       ABC-jkij     1/1        RUNNING          897
BAC       BAC-jkij     2/2        RUNNING          897
HJI       HJI-jkij     2/2        RUNNING          897

kubectl get pods | grep -v 1/1 | grep -v 2/2 | awk '{print $1:$2:$3}'

The above command will result only the headers like below as i kept -v:

NAMESPACE   NAME      READY       STATUS              RESTARTS

so in Awk we have no of records variable right, I want to put a condition in the Awk block which should print only if there are any 0/1 or 0/2 pod results, not just the headers.

So to summmarize

NAMESPACE   NAME      READY       STATUS              RESTARTS

--> awk should not print anything

NAMESPACE   NAME      READY       STATUS              RESTARTS
ABC       ABC-jkij     0/1        RUNNING               897
ABC       ABC-jkij     0/2        RUNNING               897

Awk should print only in above scenarios.

Above command will give the headers like NAME NAMESPACE STATUS as output if there are no pods in with 0/1 0/2 etc., status. Now I want to include an if condition saying if (NR >1 ) then only it should print else it should not print anything ie., headers. If I am trying to put if (NR>1) in begin block it's still printing the headers.

CodePudding user response:

You should generally avoid piping Awk into Awk; it's a scripting language, so you can put as many statements as you want.

kubectl get pods | 
awk 'NR>1 && !/1\/1|2\/2/ { a[1]=$1; a[2]=$2; a[3]=$3;
    if (!headers) print "<style>table,th,td {border:1px solid black;}</style><table>"
    headers=1
    print "<tr>"
    for (i=1; i<=3;   i) printf "<td>%s</td>\n", a[i]
    print "</tr>"
  }
  END { if (headers) print "</table>" }'

I had to guess a bit what your expected output would be but if there are glitches, I expect it should be easy to see what to fix.

  • Related