Using ripgrep (rg), can I print only the filenames which match a given pattern?

There are two separate things I'm trying to do:

  1. Match the pattern to the pathname itself (like ag -g pattern)
  2. Match the pattern to the contents of the file and print only the filename

I can't work out how to do either one.

1 Answer 1

  1. Print only the filename where the contents match:

    rg -l regex
    # OR: long-option form
    rg --files-with-matches regex
  2. Print only the directory entries (filenames) which match the given pattern under <directory>:

    rg -g '*glob*' --files <directory>

    The -g specifies a glob whose rules match .gitignore patterns.

    Precede a glob with a ! to exclude it.

    Use --iglob instead of -g for a case-insensitive glob.

    --files prints each file that would be searched without actually performing the search.

A less efficient way to do (2) would be:

rg -lg '*pattern*' . <directory>

The . says to match any character inside the files (so it won't match on empty files).

  • If you want at most one line per file, but still want to see the contents of the matching line, you can use --max-count 1 Jun 23, 2021 at 20:02
  • How to make the glob pattern match the relative path and not only the file name?
    – Elie G.
    Feb 3, 2022 at 17:03

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .