Skip to Content
Linux Shell Scripting Cookbook - Third Edition
book

Linux Shell Scripting Cookbook - Third Edition

by Clif Flynt, Sarath Lakshman, Shantanu Tushar
May 2017
Beginner
552 pages
28h 47m
English
Packt Publishing
Content preview from Linux Shell Scripting Cookbook - Third Edition

How to do it...

To print the text between line numbers or patterns, follow these steps:

  1. Print the lines of a text in a range of line numbers, M to N:
        $ awk 'NR==M, NR==N' filename

 Awk can read from stdin:

        $ cat filename | awk 'NR==M, NR==N'
  1. Replace M and N with numbers:
        $ seq 100 | awk 'NR==4,NR==6' 
        4 
        5 
        6
  1. Print the lines of text between a start_pattern and end_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/, /end/' section.txt 
        line with pattern3 
        line end with pattern4

The patterns used in awk are regular expressions.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering Linux Shell Scripting - Second Edition

Mastering Linux Shell Scripting - Second Edition

Mokhtar Ebrahim, Andrew Mallett

Publisher Resources

ISBN: 9781785881985