Languages and Scripting

Re: Using Grep to find lines with pattern 1 AND pattern 2

 
Joe Pifer
New Member

Using Grep to find lines with pattern 1 AND pattern 2

Hello,

I know you can use grep to find pattern 1 or pattern 2 etc... Can you use it to find lines that only contain 2 specfic patterns? I am searching a weblog for a specific IP address and a specific referring site starting with '?source=Ad'

So my 2 patterns would be the IP adress '1.1.1.1' and '?source=' and I only want lines that contain BOTH of these not either of them.

Thanks
7 REPLIES 7
Bill Hassell
Honored Contributor

Re: Using Grep to find lines with pattern 1 AND pattern 2

The simplest is to concatenate 2 greps:

grep 1.1.1.1 MyFile | grep '?source='

Not the most elegant, but complex awk code will be difficult to maintain.


Bill Hassell, sysadmin
Raj D.
Honored Contributor

Re: Using Grep to find lines with pattern 1 AND pattern 2

Joe, A simple awk # cat FILE| awk '/1.1.1.1/ && /\?source=Ad/'
" If u think u can , If u think u cannot , - You are always Right . "
Raj D.
Honored Contributor

Re: Using Grep to find lines with pattern 1 AND pattern 2

Or remove the cat : # awk '/1.1.1.1/ && /\?source=Ad/' FILE #cheers.
" If u think u can , If u think u cannot , - You are always Right . "
Dennis Handly
Acclaimed Contributor

Re: Using Grep to find lines with pattern 1 AND pattern 2

If you know the relative ordering of the two patterns, you can use one grep:
grep '1\.1\.1\.1.*?source='
And if you don't, you can put both orders:
grep -e '1\.1\.1\.1.*?source=' -e '?source=.*1\.1\.1\.1'
Hakki Aydin Ucar
Honored Contributor

Re: Using Grep to find lines with pattern 1 AND pattern 2

Hi,
I know you r looking for a solution with grep;

as alternatively you can use Perl:

perl -ne 'print if /1.1.1.1/|/\?source=/' Your_File
James R. Ferguson
Acclaimed Contributor

Re: Using Grep to find lines with pattern 1 AND pattern 2

Hi:

> Hakki: perl -ne 'print if /1.1.1.1/|/\?source=/'

No, this has two things very wrong. Joe only wants matches for the presence of BOTH strings on a line. Your regex specifies alternation ('|') or "or".

The second problem is that a dot character matches anything. Thus '/1.1.1.1/ will match '1a1b1c1d' just as well. This is why Dennis escaped the dot characters in his regular expression. Bill's 'grep' and Raj's 'awk' solution suffer this too.

We could do:

# perl -ne 'print if m{1\.1\.1\.1} && m{\?source=} file

...which meets Joe's needs. I chose alternate delimiters to avoid the "leaning toothpick" look.

Regards!

...JRF...
Hakki Aydin Ucar
Honored Contributor

Re: Using Grep to find lines with pattern 1 AND pattern 2

>JRF :

Thank you for correction, I was totally wrong :(

closing apostrophe not printed below :

# perl -ne 'print if m{1\.1\.1\.1} && m{\?source=} file

# perl -ne 'print if m{1\.1\.1\.1} && m{\?source=}' file