vdavid
vdavid

Reputation: 2584

awk ignores line with 0 only

I don’t know why I can not give only 0 to awk in a direct statement, e.g. if I want to output the square of a number:

$ echo 4 | awk '$0=$1*$1'
16

$ echo 3 | awk '$0=$1*$1'
9

$ echo 0 | awk '$0=$1*$1'

Why do I get nothing on the last try?

PS. it works if I write $1 in a bracketed statement:

$ echo 0 | awk '{print $1*$1}'
0

Upvotes: 1

Views: 522

Answers (1)

user8017719
user8017719

Reputation:

No, awk does not ignore a line with 0.

However, your awk command: $0=$1*$1 does not do what you think.

By default awk prints $0 if there is an statement that evaluates to true (not zero).

So, this will always print $0:

awk '1'

And this will never print $0:

awk '0'

To do what you want: to always print $0 after it has been re-calculated, you need to do:

awk '{$0=$1*$1; print}'

And so:

$ echo "0" | awk '{$0=$1*$1; print}'
0

$ echo "2" | awk '{$0=$1*$1; print}'
4

Or, without changing the value of $0, do:

$ echo "2" | awk '{print $0*$0}'

Or (shorter but less readable):

$ echo "2" | awk '{$0=$0*$0}1'
4

And, even shorter:

$ echo "4" | awk '{$0*=$0}1'
16

This last awk script is actually composed of two command lines:

awk '
     <default pattern> {      $0*=$0      }
             1         { <default action> }
    '

Which become, replacing the action by print and the condition by all:

awk ' /.*/{$0*=$0}
       1  {print $0}'

Both lines are applied to all input lines. For all lines $0 is changed, and for all input lines a print $0 is executed.

Upvotes: 5

Related Questions