unixawk

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


  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.


Solution

  • 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.