AWK If Condition is not behaving as expected

Viewed 47

I am trying a simple String comparison to filter out String values which are equal to "Time"

echo Time | awk '{ print $1 ~ !/Time/}'
output --> 0 

Also,

echo 2020-02-01-04:18:17 | awk '{ print $1 ~ !/Time/}'
output --> 1

So the above behavior correct as per requirement.

But if the date in echo command exceeding 02-Feb-2020 then sometimes it's behaving incorrectly.

example, the output of all commands should be 1, but sometimes its returning 0, Could you please point why this is happening.

echo 2020-02-03-04:18:17 | awk '{ print $1 ~ !/Time/}'
output --> 1

// This is unexpected
echo 2020-02-02-04:30:09 | awk '{ print $1 ~ !/Time/}'
output --> 0

// This is unexpected
echo 2020-02-02-04:30:09 | awk '{ print $1 ~ !/Time/}'
output --> 0

echo 2020-02-02-04:30:10 | awk '{ print $1 ~ !/Time/}'
output --> 1
1 Answers
$1 ~ !/Time/

/Time/ doesn't match $0, so it returns 0 (false). So now we have:

$1 ~ !0

!0 is 1. 1 is converted to a string in ~ context. So now we have:

$1 ~ "1"

and it returns 1 when $1 has the string 1 and 0 if it doesn't.

2020-02-03-04:18:17
              ^  ^  - prints 1

2020-02-02-04:30:09 - no "1", prints 0
2020-02-02-04:30:09 - no "1", prints 0

2020-02-02-04:30:10
                 ^  - has a "1", prints 1

Some more funny tests:

$ echo 1 | awk '{ print $1 ~ !/Time/}'
1
$ echo 0 | awk '{ print $1 ~ !/Time/}'
0
$ echo 1 Time | awk '{ print $1 ~ !/Time/}'
0
$ echo 0 Time | awk '{ print $1 ~ !/Time/}'
1
Related