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 n lines before or after a pattern in a file

Printing a section of text by pattern matching is frequently used in text processing. Sometimes we may need the lines of text before a pattern or after a pattern appears in a text. For example, consider that there is a file containing the rating of film actors where each line corresponds to a film actor's details, and we need to find out the rating of an actor along with the details of actors who are nearest to them in rating. Let's see how to do it.

Getting ready

grep is the best tool for searching and finding text in a file. Usually, grep prints a matching line or matching text for a given pattern. But the context line control options in grep enables it to print before, after, and before-after ...

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