Printing text between line numbers or patterns
We may need to print a selected portion of a file, either a range of line numbers or a range matched by a start and end pattern.
Getting ready
Awk
, grep
, or sed
will select lines to print, based on condition. It's simplest to use grep
to print lines that include a pattern. Awk is the most versatile tool.
How to do it...
To print the text between line numbers or patterns, follow these steps:
- Print the lines of a text in a range of line numbers,
M
toN
:
$ awk 'NR==M, NR==N' filename
Awk can read from stdin
:
$ cat filename | awk 'NR==M, NR==N'
- Replace
M
andN
with numbers:
$ seq 100 | awk 'NR==4,NR==6' 4 5 6
- Print the lines of text between a
start_pattern
andend_pattern
:
$ awk '/start_pattern/, /end _pattern/' filename
Consider this example:
$ cat section.txt line with pattern1 line with pattern2 line with pattern3 line end with pattern4 line with pattern5 $ awk '/pa.*3/,...