Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advanced grep unix

Tags:

unix

aix

Usually grep command is used to display the line contaning the specified pattern. Is there any way to display n lines before and after the line which contains the specified pattern?

Can this will be achieved using awk?

like image 852
Sachin Chourasiya Avatar asked Nov 06 '09 05:11

Sachin Chourasiya


People also ask

How do I grep a specific pattern in Unix?

To find a pattern that is more than one word long, enclose the string with single or double quotation marks. The grep command can search for a string in groups of files. When it finds a pattern that matches in more than one file, it prints the name of the file, followed by a colon, then the line matching the pattern.

Which is the extended version of grep?

grep understands three different versions of regular expression syntax: ``basic'' (BRE), ``extended'' (ERE) and ``perl'' (PRCE). In GNU grep, there is no difference in available functionality between basic and extended syntaxes.

What does grep \* look for?

The grep filter searches a file for a particular pattern of characters, and displays all lines that contain that pattern. The pattern that is searched in the file is referred to as the regular expression (grep stands for global search for regular expression and print out).


1 Answers

Yes, use

grep -B num1 -A num2 

to include num1 lines of context before the match, and num2 lines of context after the match.

EDIT:

Seems the OP is using AIX. This has a different set of options which doesn't include -B and -A

this link describes grep on AIX 4.3 (it doesn't look promising)

Matt's perl script might be a better solution.

like image 158
pavium Avatar answered Sep 24 '22 02:09

pavium