I have tested both of the commands.
ls -l | awk 'NR%2 != 0'
ls -l | awk 'NR%2'
I saw the difference in the output, but, I do not know how can I explain it when I am teaching it to someone else.
Could you explain to me what != 0
means exactly?
CodePudding user response:
In awk
, the variable NR
is preset with "the total number of input records seen so far". Thus, when processing the first line it is set to 1
, for the second line to 2
, etc.
The %
operator calculates the remainder of a numerical division. Thus, with NR%2
denoting the remainder when dividing the records number by 2, for the first line this computes to 1
, for the second to 0
, for the third to 1
again, and so on.
To determine whether a record is an odd row or an even row, just check whether NR%2
evaluates to 1
or to 0
, i.e. NR%2 == 1
or NR%2 == 0
. As 1
and 0
are the only possible values, one could also check for the negation of the opposite: NR%2 != 0
and NR%2 != 1
, respectively.
In awk
, a typical instruction consists of a pattern or condition (evaluating to a boolean value) and an action statement. In your case, the action statements are missing, which means the current record should be printed if the condition evaluates to true
. For convenience, if the condition evaluates to a number instead (as in your second case), the number is automatically cast to a boolean value, with 0
becomng false
, and any other value becoming true
.
Therefore, awk 'NR%2 != 0'
which evaluates to true
on every other line starting with the first, will print odd rows and skip even rows. awk 'NR%2 == 1'
will do the same. And as 1
is cast to true
, just awk 'NR%2'
will also do the same.
CodePudding user response:
My guess is that you need to teach that someone else about modular arithmetic first. Then it should be easier to explain the AWK part.