awk Useful one-liners - calculating average from a CSV etc Selecting a set of lines between two patterns


Example

Pattern matching can be used effectively with awk as it controls the actions that follows it i.e. { pattern } { action }. One cool use of the pattern-matching is to select multiple between two patterns in a file say patternA and patternB

$ awk '/patternA/,/patternB/' file

Assume my file contents are as follows, and I want to extract the lines only between the above pattern:-

$ cat file
This is line - 1
This is line - 2
patternA
This is line - 3
This is line - 4
This is line - 5
patternB
This is line - 6

$ awk '/patternA/,/patternB/' file
patternA
This is line - 3
This is line - 4
This is line - 5
patternB

The above command doesn't do any specific { action } other than to print the lines matching, but any specific actions within the subset of lines can be applied with an action block ({}).