Tux

...making Linux just a little more fun!

Searching for multiple strings/patterns with 'grep'

Amit k. Saha [amitsaha.in at gmail.com]


Mon, 23 Jun 2008 11:52:44 +0530

Hello TAG,

I have a text file from which I want to list only those lines which contain either pattern1 or patern2 or both.

How to do this with 'gre'p?

Assume, file is 'patch', and 'string1' and 'string2' are the two patterns.

The strings for me are: 'ha_example' and 'handler'- so I cannot possibly write a regex for that.

Thanks, Amit

-- 
Amit Kumar Saha
http://blogs.sun.com/amitsaha/
http://amitksaha.blogspot.com


Top    Back


Kapil Hari Paranjape [kapil at imsc.res.in]


Mon, 23 Jun 2008 12:36:12 +0530

Hello,

On Mon, 23 Jun 2008, Amit k. Saha wrote:

> I have a text file from which I want to list only those lines which
> contain either pattern1 or patern2 or both.
	grep -e '(pattern1)|(pattern2)'
or
	grep '\(pattern1\)\|\(pattern2\)'

Regards,

Kapil. --


Top    Back


Ben Okopnik [ben at linuxgazette.net]


Mon, 23 Jun 2008 07:41:56 -0400

On Mon, Jun 23, 2008 at 11:52:44AM +0530, Amit k. Saha wrote:

> Hello TAG,
> 
> I have a text file from which I want to list only those lines which
> contain either pattern1 or patern2 or both.
> 
> How to do this with 'gre'p?
> 
> Assume, file is 'patch', and 'string1' and 'string2' are the two patterns.
> 
> The strings for me are: 'ha_example' and 'handler'- so I cannot
> possibly write a regex for that.

Over the years, I've developed a working practice that says "don't use grep for anything more than a simple/literal search." Remembering the bits that you have to escape vs. those you don't is way too much of a pain. Stick with 'egrep', and you don't have to remember all that stuff.

egrep 'string1|string2' filepattern

If you really, really want to use 'grep' itself:

grep 'string1\|string2' filepattern

Bleh.

By the way, simple tip: if you're not sure about the regex you're using, just use STDIN as your input:

ben@Tyr:~$ grep 'foo\|bar'
abc
foo
foo
bar
bar
xyz

I entered 'abc', 'foo', 'bar', and 'xyz'; note that 'grep' echoed all the matching lines. Terminate input with 'Ctrl-D'.

-- 
* Ben Okopnik * Editor-in-Chief, Linux Gazette * http://LinuxGazette.NET *


Top    Back