Selective printing of lines with AWK

In this section, we look at various one liners used for printing lines of a file selectively with AWK:

  • Printing the top 10 lines of a file (similar to the head 10 shell command): In this example, we use a built-in AWK variable called NR with an input of record number/line number. After reading each line, AWK increments this variable value by one. An AWK action statement gets executed for each pattern match. In this example, we do not specify any action statements. In the absence of any action statement, the default operation is print. So, it will print the line, if the line number is less than 11, as follows:
$ awk 'NR < 11' cars.dat

The previous command processes all the lines in a file, although in ...

Get Learning AWK Programming 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.