O'Reilly logo

Linux Shell Scripting Cookbook by Sarath Lakshman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Printing text between line numbers or patterns

We may require to print certain section of text lines based on conditions such as a range of line numbers, range matched by start and end pattern and so on. 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...

In order to print lines of text in a range of line numbers, M to N, use the following syntax:

$ awk 'NR==M, NR==N' filename

Or, it can take stdin input as follows:

$ cat filename | awk 'NR==M, NR==N'

Replace M and N with numbers as follows:

$ seq 100 | awk 'NR==4,NR==6'
4
5
6

To print lines of text in a section with ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required