Searching multiple patterns (words) with ack?

2019-02-09 22:49发布

I want to search multiple patterns in a directory containing recursive directories and files.

I know command for grep which is as follows

grep -e '(pattern1)|(pattern2)'

or

grep -r -E  'string1|string2|string3' /var/www/http

What is the command for that using ack or ag?

标签: linux grep ack ag
3条回答
在下西门庆
2楼-- · 2019-02-09 23:05

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.

查看更多
地球回转人心会变
3楼-- · 2019-02-09 23:10

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 star\"
4楼-- · 2019-02-09 23:10

I don't know why but for my use case, the pipe solution didn't work.

I simply used the output of ack -l as the input to grep. For example, to quickly find all Javascript files containing string 1 and string 2:

grep "string 2" `ack -l --js "string 1"`
查看更多
登录 后发表回答