home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam    

UNIX Power Tools

UNIX Power ToolsSearch this book
Previous: 27.10 Search RCS Files with rcsgrep Chapter 27
Searching Through Files
Next: 27.12 Make Custom grep Commands (etc.) with perl
 

27.11 A Multiline Context grep Using sed

[One weakness of the grep family of programs is that they are line-oriented. They read only one line at a time, and so they can't find patterns (such as phrases) that are split across two lines. agrep (27.8 ) can do multiline searches. One advantage of the cgrep.sed script is that it shows how to handle multiple-line patterns in sed -and can be adapted for work other than searches. -JP ]

cgrep.sed
It may surprise you to learn that a fairly decent context grep program can be built using sed (34.1 ) . This sed version of cgrep is used the same way as the Perl version in article 27.13 :

$ cgrep -10 system main.c

will find all lines containing the word system in the file main.c , and show 10 additional lines of context above and below each match. (The -context option must be at least 1, and defaults to 2 lines.) It differs from the Perl version in that, if several matches occur within the same context, the lines are printed as one large "hunk" rather than repeated smaller hunks. Each new block of context is preceded by the line number of the first occurrence in that hunk. This script can also search for patterns that span lines:

cgrep -3 "awk.*perl"

will find all occurrences of the word "awk" where it is followed by the word "perl" somewhere within the next 3 lines. The pattern can be any simple regular expression (26.4 ) , with one notable exception: because you can match across lines, you should use \n in place of the ^ and $ metacharacters.

Article 34.17 explains how the script works.

- GU


Previous: 27.10 Search RCS Files with rcsgrep UNIX Power Tools Next: 27.12 Make Custom grep Commands (etc.) with perl
27.10 Search RCS Files with rcsgrep Book Index 27.12 Make Custom grep Commands (etc.) with perl

The UNIX CD Bookshelf NavigationThe UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System










??????????????@Mail.ru