0

What's the ack syntax to find all files containing foo and also bar?

student
  • 17,875
  • 31
  • 103
  • 169
  • 1
    Given that `ack` is (almost) a drop-in replacement for `grep`, the answers in [How to search files where two different words exist?](http://unix.stackexchange.com/questions/67794/how-to-search-files-where-two-different-words-exist) should work here too. – roaima Sep 01 '16 at 22:40

1 Answers1

4

First we need to select the files that contain foo and, from that list of files, selects files that also contain bar. Thus:

ack -l foo | ack -x bar

As you can see, this works in two steps:

  1. ack -l foo produces a list of the names of files that contain foo.

  2. ack -x bar searches the files named on stdin for the expression bar.

John1024
  • 73,527
  • 11
  • 167
  • 163
  • Shouldn't that first bit be `ack -l foo *` ? – roaima Sep 01 '16 at 22:43
  • 1
    @roaima If no files or directories are given on the command line, `ack` defaults to searching recursively starting with the current directory. This default is similar to `grep -r pattern`. Your approach. of course, would work also. – John1024 Sep 01 '16 at 22:54
  • 1
    Thank you. It's a new command to me, but the man page seemed to jump on the "it's a drop-in for `grep`" line. (I'll delete this later. Or maybe you can.) – roaima Sep 01 '16 at 22:56
  • @roaima Yes, it is similar but different. To make it more like `grep`, I have a `~/.ackrc` file that contains `--no-recurse`. (I can, of course, override that on the command line with `ack -r`.) – John1024 Sep 01 '16 at 22:59