ack - search for multiple patterns (logical AND)
Asked Answered
T

3

7

How to search file with the ack to find lines containing ALL (nor any) of defined patterns?

the ANY (OR) is easy, like:

ack 'pattern1|pattern2|pattern3'

but how to write the AND (ALL) ? e.g. how to write the following:

if( $line =~ /pattern1/ && $line =~ /pattern2/ && $line =~ /pattern3/ ) {
    say $line
}

using ack?

Or more precisely, is possible create an regex with logical and?

Taster answered 28/3, 2016 at 16:59 Comment(0)
O
6
 /foo/s && /bar/s && /baz/s

can be written as

 /^(?=.*?foo)(?=.*?bar)(?=.*?baz)/s

We don't actually need a look ahead for the last one.

 /^(?=.*?foo)(?=.*?bar).*?baz/s

And since we don't care which instance of the pattern is matched if there are more than one, we can simplify that to

 /^(?=.*foo)(?=.*bar).*baz/s
Offshore answered 28/3, 2016 at 18:36 Comment(1)
Thanks! Also: Is there really no easier option?Forbis
D
5

Simplest solution is to apply progressive filtering via chained calls to ack:

$ ack pattern1 | ack pattern2 | ack pattern3 | ...
Diphthongize answered 28/3, 2016 at 17:3 Comment(2)
yes ;) this is possible with the grep too. isn't possible in one ack run? - e.g. perl-regexes doesn't knows something as AND?Taster
@cajwine: Regular expressions do patterns, not logic. To be a bit pedantic: inside a regex the | means "alternation," not "or." There's no meta-character for an "and" because that's the implicit default. e.g. the pattern ab requires matching the character "a" and the character "b" (in that order, and adjacent to each other). Matching multiple patterns requires either multiple matches (as in amphetamachine's answer) or merging the patterns into a single one (as in ikegami's answer).Rambo
B
3

I had a similar use case where I wanted to find files that contained multiple patterns but (possibly) on different lines.

ack -l 'pattern1' | ack -xl 'pattern2'

This allowed me to find files that were using 2 libraries together.

Burnsides answered 26/10, 2018 at 19:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.