(How) Can I find files where there are occurrences of 2 words in that same file, say Peter
and James
? Is it possible with ack-grep
?
Asked
Active
Viewed 971 times
1

Bentley4
- 10,678
- 25
- 83
- 134
-
I want to find files that have at least one occurence of `Peter` and at least one occurence of `James`. – Bentley4 Feb 23 '13 at 16:11
1 Answers
2
You can just grep twice:
grep -l Peter * | xargs grep -l James
The same works with ack
:
ack -l Peter * | xargs ack -l James
You can replace the *
with whatever other file list you might care about, or use find
to generate a list for you.

Carl Norum
- 219,201
- 40
- 422
- 469
-
I tried this and it does not seem to work. Btw I'm searching for files in the current directory and want to search in every file in that directory or subdirectory (as `ack-grep` does by default). – Bentley4 Feb 23 '13 at 16:20
-
Strange, I used an alias for `ack-grep` and with that alias it returned `xargs: ag: No such file or directory` with `ag` being my `ack-grep` alias. But with using the full name `ack-grep` it did work. – Bentley4 Feb 23 '13 at 16:24
-
1@Bentley4 - I think you've just found out why aliases aren't always all they're cracked up to be. – Carl Norum Feb 23 '13 at 16:26
-
Is there a way to also show the lines where any of these words appear in for those files? When I do `ack-grep -l Peter * | xargs ack-grep James` only the lines are shown in those files where `James` appears in not surprisingly. But `ack-grep Peter * | xargs ack-grep James` does'nt output anything at all. – Bentley4 Feb 23 '13 at 16:35
-
Sure, just add another `| xargs grep -n 'James\|Peter'` to the end. – Carl Norum Feb 23 '13 at 16:53
-
When I do that however it searches from the root, not from my current directory even when I use ack-grep. Any ideas? – Bentley4 Feb 23 '13 at 16:58
-
@Bentley4, that means you have the wrong search path set up in your first command. – Carl Norum Feb 24 '13 at 19:09
-
This was the command I was looking for: `ack-grep -l Peter | xargs ack-grep -l James | xargs ack-grep 'Peter|James'` – Bentley4 Feb 24 '13 at 23:09