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

From: Michael Schuster <michaelsprivate_at_gmail.com>
Date: Thu, 08 Sep 2022 04:44:40 UTC
On Thu, Sep 8, 2022 at 5:43 AM Carl Johnson <carlj@peak.org> wrote:
>
> Aryeh Friedman <aryeh.friedman@gmail.com> writes:
>
> > 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.

I put together a simple awk-version (on linux, but there shouldn't be
much difference to BSD) - consider this a start, not a solution:
--- begin multigrep.awk
/foo/ {foo_line=NR; if (bar_line > 0) { printf "%d; %d\n", foo_line,
bar_line; exit } }
/bar/ {bar_line = NR; if (foo_line > 0) { printf "%d; %d\n", foo_line,
bar_line; exit } }
--- end multigrep.awk

HTH

> >
> > 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.
>
> I use grep -l to just return a list of files that contain one pattern,
> and then grep -l for the second pattern on that list.  That can be done
> in one line for your example as follows:
>
>   grep -li /tmp `grep -liR tid src/java`
>
> I hope that gives you some ideas.
> --
> Carl Johnson            carlj@peak.org
>


--
Michael Schuster
http://recursiveramblings.wordpress.com/
recursion, n: see 'recursion'