62

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.

Tom Hale
  • 28,728
  • 32
  • 139
  • 229

1 Answers1

92
  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).

Gabriel Staples
  • 2,192
  • 1
  • 24
  • 31
Tom Hale
  • 28,728
  • 32
  • 139
  • 229