Operating System - HP-UX
1823079 Members
3229 Online
109645 Solutions
New Discussion юеВ

Re: want to grep lines which is having multiple strings pattern

 
ezhilarasan_1
Occasional Advisor

want to grep lines which is having multiple strings pattern

Hi,

I want to grep lines which is having multiple strings pattern.
Suppose I have some files, I want to find lines which contain two words like "Ezhil" and "Arasan".

grep -i "Ezhil" *.txt --> gives all the lines ( with filename ) which contan this pattern.

I do not want all these lines, wanted to see only lines with AND another word "Arasan".

what command syntax will help for this ?

Thanks
Ezhil
6 REPLIES 6
Rajeev  Shukla
Honored Contributor

Re: want to grep lines which is having multiple strings pattern

Hi Ezhil,

Try this

grep -i "Ezhil" *.txt |grep -i Arasan

this will give you lines which have both Ezhil and Arasan...take care of -i for case sensitivity..

Cheers
Rajeev
Siddhartha M
Frequent Advisor

Re: want to grep lines which is having multiple strings pattern

Use:

grep Eizhil *.txt | grep Arasan


H.Merijn Brand (procura
Honored Contributor

Re: want to grep lines which is having multiple strings pattern

both above answers are right. Perl is easier on this

# perl -ne'/Ezhil/&&/Arasan/ and print' *.txt

Enjoy, Have FUN! H.Merijn
Enjoy, Have FUN! H.Merijn
Hein van den Heuvel
Honored Contributor

Re: want to grep lines which is having multiple strings pattern


>> perl -ne'/Ezhil/&&/Arasan/ and print' *.txt

And without the case-insensitive requirement suggested, and without having to print the file name as requested an awk solution it is a touch easier still:

awk '/Ezhil/&&/Arasan/' *.txt

However, to fullfill all the requirements I think you'd need:

awk 'BEGIN {IGNORECASE=1} /Ezhil/&&/Arasan/ { print FILENAME ":" $0}' *.txt

So in general, I'd just stick to the multiple greps as suggested.

Hein.


H.Merijn Brand (procura
Honored Contributor

Re: want to grep lines which is having multiple strings pattern

With filename:

# perl -ne'/Ezhil/&&/Arasan/ and print"$ARGV:$_"' *.txt

And case insensitiviness

# perl -ne'/Ezhil/i&&/Arasan/i and print"$ARGV:$_"' *.txt

And also word only (GNU grep supports -w for that, but a lot of other grep versions do not):

# perl -ne'/\bEzhil\b/i&&/\bArasan\b/i and print"$ARGV:$_"' *.txt

So using GNU grep case-insensitive

# grep -w -i ezhil *.txt | grep -w -i arasan

One small problem left there, if there is only one .txt file, in which case the file name is NOT prepended to the output. You can force that by grepping /dev/null:

# grep -w -i ezhil *.txt /dev/null | grep -w -i arasan

Enjoy, Have FUN! H.Merijn
Enjoy, Have FUN! H.Merijn
James R. Ferguson
Acclaimed Contributor

Re: want to grep lines which is having multiple strings pattern

Hi:

...but adding case-insensitive matching to the perl offering is *so easy* :-))

# perl -ne' /Ezhil/i && /Arasan/i and print' *.txt

Regards!

...JRF...