Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if the variable value in AWK script is null or empty?

Tags:

unix

awk

  1. I am using AWK script to process some logs.
  2. At one place I need to check if the variable value is null or empty to make some decision.

Any Idea how to achieve the same?

awk '  {     {        split($i, keyVal, "@")        key=keyVal[1];        val=keyVal[2];        if(val ~ /^ *$/)        val="Y";      }  }  ' File 

I have tried with

1) if(val == "")  2) if(val ~ /^ *$/) 

not working in both cases.

like image 265
samarth Avatar asked Aug 14 '12 13:08

samarth


People also ask

What does $0 represent in awk?

In awk, $0 is the whole line of arguments, whereas $1 is just the first argument in a list of arguments separated by spaces.


2 Answers

The comparison with "" should have worked, so that's a bit odd

As one more alternative, you could use the length() function, if zero, your variable is null/empty. E.g.,

if (length(val) == 0) 

Also, perhaps the built-in variable NF (number of fields) could come in handy? Since we don't have access to your input data it's hard to say though, but another possibility.

like image 196
Levon Avatar answered Oct 07 '22 22:10

Levon


You can directly use the variable without comparison, an empty/null/zero value is considered false, everything else is true.

See here :

# setting default tag if not provided if (! tag) {         tag="default-tag" } 

So this script will have the variable tag with the value default-tag except if the user call it like this :

$ awk -v tag=custom-tag -f script.awk targetFile 

This is true as of : GNU Awk 4.1.3, API: 1.1 (GNU MPFR 3.1.4, GNU MP 6.1.0)

like image 29
Adrien H Avatar answered Oct 07 '22 22:10

Adrien H