Counting matched rows

We may also want to count the number of rows returned by the filter. For example, using the internal NR variable will show all rows and not just matched rows; for us to be able to report the number of users that have logged in, we must use our own variable. The following code will maintain the count within the variable that we name cnt. We increment this using the C style ++ for each iteration of the main code block.

We can use the END code block to display the closing value of this variable:

!(/Never logged in/ || /^Username/ || /^root/) { 
  cnt++ 
  print $0; 
} 
END { 
  print "========================" 
  print "Total Number of Users Processed: ", cnt 
} 

We can see from the following code and output how this appears on my system: ...

Get Mastering Linux Shell Scripting now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.