Operating System - HP-UX
1834050 Members
2190 Online
110063 Solutions
New Discussion

Re: grep for word in text files but show neighbouring lines

 
Matt Murphy_1
Occasional Contributor

grep for word in text files but show neighbouring lines

Is there a grep utility that will allow me to search for a string in a series of text files (programs) but that will also allow a number of lines before and after the good line to be included.

Thanks,

Matt.
5 REPLIES 5
Pete Randall
Outstanding Contributor

Re: grep for word in text files but show neighbouring lines

Matt,

I'm attaching the "handy one-liners for sed". I believe you'll find your solution there (if you don't mind using sed, that is).


Pete


Pete
Rodney Hills
Honored Contributor

Re: grep for word in text files but show neighbouring lines

I believe the gnu version of "grep" has a -w option to display a number of lines before and after.

see http://hpux.cs.utah.edu/ to get a copy.

HTH

-- Rod Hills
There be dragons...
Stuart Browne
Honored Contributor

Re: grep for word in text files but show neighbouring lines

The flags for GNU's grep are -An, -Bn and -Cn.

-A or --after-context
-B or --before-context
-C or --context

Each is followed by the number of lines you want before/after.

If you don't want to use GNU's grep though, you will have to use something like the sed solution posted above.
One long-haired git at your service...
Hein van den Heuvel
Honored Contributor

Re: grep for word in text files but show neighbouring lines


I'm afraid an sed or perl script will be the
way unless gnu-grep can be obtained.

Now if this question wat for one of HP's other fine operating systems then the anwer is easier.
Under OpenVMS it would be SEARCH/WINDO=(before,after).
Under Tru64: grep -p [for paragraph]

-pparagraph_separator
[Tru64 UNIX] Displays the entire paragraph containing matched lines.
Paragraphs are delimited by paragraph separators, paragraph_separator,
which are patterns in the same form as the search pattern. Lines con-
taining the paragraph separators are used only as separators; they are
never included in the output. The default paragraph separator is a
blank line.


Cheers,
Hein.
john korterman
Honored Contributor

Re: grep for word in text files but show neighbouring lines

Hi Matt,

I fiddled with an awk command and put into the attached script. You can try running it like this:

#

which tries to find all occurrances of the string "murphy" plus the two lines proceeding and following "murphy" in the syslog.

regards,
John K.


it would be nice if you always got a second chance