Printing text between line numbers or patterns
We may require to print a certain section of text lines, based on conditions such as a range of line numbers, and a range matched by a start and end pattern. Let's see how to do it.
Getting ready
We can use utilities such as awk
, grep
, and sed
to perform the printing of a section based on conditions. Still, I found awk
to be the simplest one to understand. Let's do it using awk
.
How to do it...
- To print the lines of a text in a range of line numbers,
M
toN
, use the following syntax:$ awk 'NR==M, NR==N' filename
Or, it can take the
stdin
input as follows:$ cat filename | awk 'NR==M, NR==N'
- Replace
M
andN
with numbers as follows:$ seq 100 | awk 'NR==4,NR==6' 4 5 6
- To print the lines of a text in a ...
Get Linux Shell Scripting Cookbook - Second Edition 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.