How does this awk command work?

The following remarkably complex command will print all lines after the first occurrence of the 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 did not come up with this, it was posted on compgroups.net .)

+4
source share
2 answers

So awk '/foo/,/bar/{print $0}' file will print every line in the file from foo to bar .

This syntax /foo/,/bar/ is called a range pattern. If the first constant expression /foo/ matched, the block will execute until the second constant expression /bar/ is matched. By setting the constant constant expression to 0 (i.e., False), it will never be matched, so the block runs in each line to the end of the file.

In awk , if you do not specify a block code to execute for the condition, then the default block is {print $0} .

+4
source

On the awk page:

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

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

Here the first is /pattern/ , and the second is the literal constant 0 , which is false. Thus, it starts with the first line that matches, and stops when the line does not exist at all, which happens only after the file completes.

As another example, compare:

 jot 10 

from:

 jot 10 | awk 'NR==4,NR==6 { printf("line %d: %s\n", NR, $0) }' 
+5
source

Source: https://habr.com/ru/post/1497326/


All Articles