Searching multiple patterns (words) with ack?

For ag, as of verion 0.19.2 the default is to search in directories and files recursively.

To search for multiple patterns, you can use similiar syntax as ack

ag 'pattern1|pattern2'

will search for both pattern1 and pattern2.

In case you don't want to search recursively, you can set the search depth to 1 by the switch --depth NUM

Therefore,

ag 'pattern1|pattern2' --depth 1

will only search in the current directory for both patterns.


This should be enough:

ack -R 'string1|string2'

As -R is the default, you can omit it:

ack 'string1|string2'

From man ack:

-r, -R, --recurse

Recurse into sub-directories. This is the default and just here for compatibility with grep. You can also use it for turning --no-recurse off.


If you want to get the pattern from a file, say /path/to/patterns.file, you can use:

ack "$(cat /path/to/patterns.file)"

or equivallently:

ack "$(< /path/to/patterns.file)"

I cannot find an exact equivalent to grep -f.


The ack command can also string along with pipes. For example the first ack finds files containing pattern1 then pipe that to another ack to search just those files for pattern2

ack -l 'pattern1' | ack -x 'pattern2'

The -l parameter means to just list the matching files (instead of the matching text). The -x parameter means to search just the files piped to it. This is similar to narrowing down the files for the next ack search.

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

This is an AND operator and not the OR operator given in the other solutions.

Tags:

Linux

Grep

Ack

Ag