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

UnixAwk

Unix Problem Overview


  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.

Unix Solutions


Solution 1 - Unix

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.

Solution 2 - Unix

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)

Solution 3 - Unix

It works just fine for me

$ awk 'BEGIN{if(val==""){print "null or empty"}}'
null or empty

You can't differentiate between variable being empty and null, when you access "unset" variable, awk just initializes it with default value(here it is "" - empty string). You can use some sort of workaround, for example, setting val_accessed variable to 0 and then to 1 when you access it. Or more simple approach(somewhat "hackish") setting val to "unitialized"(or to some other value which can't appear when running your program).

PS: your script looks strange for me, what are the nested brackets for?

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsamarthView Question on Stackoverflow
Solution 1 - UnixLevonView Answer on Stackoverflow
Solution 2 - UnixAdrien HView Answer on Stackoverflow
Solution 3 - UnixAlexander PutilinView Answer on Stackoverflow