With rg I want to list all files which contain PATTERN_A and PATTERN_B, possibly on different lines, but both patterns should be in the file.
I tried
rg -l -e PATTERN_A -e PATTERN_B /path/to/dir
but this finds all files containing PATTERN_A or PATTERN_B (or both, but not only files containing both patterns).
How can I find with rg all files contain both patterns?
ripgrep can't really do this on its own. You could concoct something with the
-U/--multilineflag, but the most robust way is to use shell pipelines andxargs.First, the setup:
And now the command:
The
-l/--files-with-matchesflag tells ripgrep to only print the file path of files containing at least one match. The-0flag tells ripgrep to print the file paths terminated by NUL instead of by the newline character. Piping this intoxargs -0causes each NUL terminated string from ripgrep to get turn into a CLI argument to its sub-command,rgin this case. The secondrgcommand searches for the second term,bazand also asks ripgrep to print only the files matched. The result is a list of file paths containing bothfooandbaz, not necessarily on the same line.