9

I'd like ripgrep to search paths with the specified pattern. For e.g.

rg PATTERN --path REGEX

where PATTERN is the pattern to grep and REGEX is the path matching pattern.

I have scattered through the documentation and I am unsure if this functionality is baked in.

p0lAris
  • 193
  • 1
  • 4
  • Lets be clear this is solvable using `rg -l PATTERN | grep -E REGEX` but I'd prefer to be more efficient and search only in files that match the pattern. – p0lAris Feb 26 '19 at 16:42

2 Answers2

11

Use the -g/--glob flag, as documented in the guide. It uses globbing instead of regexes, but accomplishes the same thing in practice. For example:

rg PM_RESUME -g '*.h'

finds occurrences of PM_RESUME only in C header files in my checkout of the Linux kernel.

ripgrep provides no way to use a regex to match file paths. Instead, you should use xargs if you absolutely need to use a regex:

rg --files -0 | rg '.*\.h$' --null-data | xargs -0 rg PM_RESUME

Breaking it down:

  • rg --files -0 prints all of the files it would search, on stdout, delimited by NUL.
  • rg '.*\.h$' --null-data only matches lines from the file list that end with .h. --null-data ensures that we retain our NUL bytes.
  • xargs -0 rg PM_RESUME splits the arguments that are NUL delimited, and hands them to ripgrep, which precisely corresponds to the list of files matching your initial regex.

Handling NUL bytes is necessary for full correctness. If you don't have whitespace in your file paths, then the command is simpler:

rg --files | rg '.*\.h$' | xargs rg PM_RESUME
BurntSushi5
  • 530
  • 5
  • 6
  • Can you add an example to demonstrate an exclude glob? I can't seem to get it to work: `rg --color=always 'regex_search' -g '!some/path/*' | tee rg.txt`. Files in path `some/path/*` are still being searched! – Gabriel Staples Sep 18 '20 at 20:24
  • Nevermind! It works. The problem was it was finding patterns in my previous "rg.txt"-type output files. I just had to move or delete them. – Gabriel Staples Sep 18 '20 at 20:37
  • This began working for me once I added `-.` (or `--hidden`) since I was searching for files in `.github` folder – Ashutosh Jindal Mar 27 '22 at 10:01
2

You could use fd:

$ fd -p REGEX | xargs rg PATTERN
Matt
  • 757
  • 1
  • 8
  • 9