Trevor
Starfighter Starfighter
Starfighter
  • 80 Views

awk Tip - #6

$  awk 'NR > 8  &&  NR < 12'   /etc/passwd

This command will display lines 9, 10, and 11 on the screen.

What I'm featuring in this example are the following:
-  NR
-  &&
-  >  and  <

Let me start with the operators that you probably don't need any introduction to,
and that's:   &&, >, and <.

&& is our logical AND operator.  As is always the case, it has 2 operands - in the case of this example, the operand on the left is NR > 8, and the operand on the right is NR < 12.  I'll come back to the relational expression NR > 8  and  NR < 12 in a moment.

Let's talk about NR for a moment.  NR is one of awk's special (built-in) variables.  NR refers to the current record that is being read by awk, from the start of the input. Stated another way, NR refers to the number of input records that awk has processed since the start of the awk execution.  I'll provide an example of this variable in a separate awk Tip - I don't want to overload this one.

For each line that awk reads, that line represents a Record Number (NR) - as you might expect, line 1 refers to record 1 (NR is 1), line 2 refers to record 2 (NR is 2), so on, and so on.  Each line that is read, has the awk statement of NR > 8 && NR < 12  evaluated.  In the case of the first line (record), the statement that is essentially evaluated is:   1 > 8 && 1< 12.  We know that this operation evaluates to a FALSE condition because:  FALSE (1>8) && TRUE (1<12) ==>  FALSE.   Which means that no action (by default, printout the current line) will be taken on line.  There will ONLY be a TRUE condition for the logical AND operation when, NR equals 9 (line 9 is being read), NR equals 10 (line 10 is being read), and NR equals 11 (line 11 is being read). 

Again, the value of the built-in variable NR changes each time awk reads the next line.

If you've done any BASH shell scripting, I know you're familiar with relational and logical operators (and operations).  Not wanting to assume that everyone has been exposed to BASH shell scripting, or any programming language, I provide some explanation of what's going on with this &&, <, and > sign.

In closing, let me say that there's nothing magical about my use of the /etc/passwd file.  Any file, with any content would have served the purpose.  I just wanted to use a file that I'm sure everyone has some familiarity with, and not make that the focus, but the NR variable and operators, instead.

Hit me up - that's the hip way of saying reachout to me - if you have any questions!

 

 

Trevor "Red Hat Evangelist" Chandler
Labels (3)
0 Replies
Join the discussion
You must log in to join this conversation.