Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this awk command work?

Tags:

awk

The following remarkably terse command will print all of the lines after the first occurrence of a pattern (including the first occurrence):

awk '/pattern/,0'

Can someone explain how this command works? How does awk parse '/pattern/,0'?

(By the way, I didn't come up with this; it was posted on compgroups.net.)

like image 889
Max Radin Avatar asked Jan 13 '23 15:01

Max Radin


1 Answers

Per the awk man page:

Patterns are arbitrary Boolean combinations (with ! || &&) of regular expressions and relational expressions. ...

A pattern may consist of two patterns separated by a comma; in this case, the action is performed for all lines from an occurrence of the first pattern though an occurrence of the second. ...

Here the first one is /pattern/ and the second is a literal constant 0, which is false. So this starts at the first line that matches, and stops when a line does not exist at all, which only occurs after the file ends.

As another example, compare:

jot 10

with:

jot 10 | awk 'NR==4,NR==6 { printf("line %d: %s\n", NR, $0) }'
like image 83
torek Avatar answered Mar 24 '23 02:03

torek