Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

logical AND with grep

Status
Not open for further replies.

Martin999

Technical User
Feb 26, 2004
298
US
Guys,

Don't laugh ...

Have a couple of variables, would like to grep for VAR1 AND var2 in a file.

AWK is a possible, but need to pass the variables into it ...

grep is possible,

grep var1 filename |grep var2 .. but not neat ...

and better ways ???

Thanks,

Martin
 
This works on my Solaris box...
Code:
/usr/xpg4/bin/grep -x -E 'VAR1|var2' file.dat
The [tt]-E[/tt] allows you to specify multiple patterns, and the [tt]-x[/tt] makes it return only records that match ALL patterns (a logical AND).

Hope this helps.
 
Hi

Interesting [tt]grep[/tt] feature, SamBones. Could you tell me, please, more about that [tt]grep[/tt] ? I have GNU [tt]grep[/tt] 2.5.1, and -x means --line-regexp. But that logical AND feature looks much usefull.

Feherke.
 
ahhn, the old -x - missed that when I looked through the an page ....

Thanks you very much, i shall give it a go.

all the best

Martin
 
I agree with Feherke, my understanding is that -x is supposed to force a match of the entire line... I don't understand why it allows partial line matches when you use alternation (i.e. |) with -E; maybe that's a bug?!

Sam, your solution doesn't do exactly what Martin requires, because it still matches a line containing only "var1" or "VAR2".

An alternative is egrep 'var1.*VAR2|VAR2.*var1' (or use grep -E if you prefer).

Annihilannic.
 
Thanks Annihilannic, I think you may be right, I have a feeling (thinking back) that -x doesn't always do what you require.

You method looks good, didn't think of that ...

Martin
 
AWK is a possible, but need to pass the variables into it ...
Not necessarly:
v1=VAR1; v2=var2
awk "/$v1/ && /$v2/" filename

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ181-2886
 
PHV,

wow, thanks, you always come up with some clever answer ...

Many thanks,

Martin
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top