Search code examples
ag

How can I search only files that start with a certain character using ag?


Let's say I have two files in a directory:

.test
test.txt

How can I limit my ag search to only files that begin with a .?

I have tried a number of patterns, but none worked.


Solution

  • How can I limit my ag search to only files that begin with a .?

    Like this:

    ag -u -G ^\..*$ PATTERN
    

    In your example, the file .test is hidden, so the option -u comes in handy. This option is probably what you missed in your search.

    Let me explain the regular expression ^\..*$:

    • ^ means: the beginning of the string
    • \. means: a dot character
    • .* means: any character (.) any number of times (*)
    • $ is optional; it marks the end of the string to match

    Note: I opened a bug tracker for ag, because I see the search is not limited to files whose names start with . as it should be for this regular expression.


    More generally, to search PATTERN in files whose names match REGEX, one can use:

    ag -G REGEX PATTERN
    

    (same as ag --file-search-regex REGEX PATTERN)

    Check the manual for more information on ag.