Re: Slightly OT: How to grep for two different things in a file

From: Andreas Kusalananda Kähäri <andreas.kahari_at_abc.se>
Date: Mon, 12 Sep 2022 06:42:16 UTC
On Mon, Sep 12, 2022 at 04:21:57AM +0000, doug wrote:
> On Wed, 7 Sep 2022, Aryeh Friedman wrote:
> 
> > I have 2 patterns I need to find in a given set of files.  A file only
> > matches if it contains *BOTH* patterns but not in any given
> > relationship as to where they are in the file.   In the past I have
> > used piped greps when both patterns are on the same line but in my
> > current case they are almost certainly not on the same line.
> >
> > For example my two patterns are "tid" (String variable name) and
> > "/tmp" [String literal] (i.e. the full string is the concatenation of
> > the two patterns I would do:
> >
> > grep -Ri tid src/java|grep -i /tmp
> >
> > But since /tmp is in a symbolic constant defined elsewhere (in a
> > different Java file) I need to find programmatically either the name
> > of the constant (has different names in different classes) and then do
> > the piped grep above with it or I need to look for the two patterns
> > separately and say a file is only accepted if it has both.
> >
> > P.S. The reason for this is I am attempting to audit my code base to
> > see what classes leave behind orphaned temp files.
> >
> > -- 
> > Aryeh M. Friedman, Lead Developer, http://www.PetiteCloud.org
> 
> Apologies if someone that whis and I missed it.
> 
> egrep "pattern1|pattern2|..." files
> 
> If the patterns contain $|"' etc it get trickier but this works for 90% of 
> what I what to do from day-to-day

I believe that the initial issue was that the user wanted *all* patterns
to match somewhere in the file, not just one of the patterns.  For that,
you need to use multiple grep invocations, or to be a bit more creative
with a scripting language such as awk.

-- 
Andreas (Kusalananda) Kähäri
SciLifeLab, NBIS, ICM
Uppsala University, Sweden

.