Search code examples
command-lineterminalgrepag

Silver Searcher: How can I only return results in folders matching a pattern?


My file structure is like this:

A
   G (want to ignore)
   H (want to ignore)
   X (contains files I want to search)
B
   G (want to ignore)
   H (want to ignore)
   X (contains files I want to search)
C (want to ignore)
X (contains files I want to search)

I want to only return results where X is somewhere the directory path.

It looks like I could use ag foo --ignore={G,H} but the list of folders to ignore would be very (almost prohibitively) long. I normally want to search in ALL of the folders so I could manually construct a global ignore file with everything and swap it in place when I want to ignore mostly everything.

I found that this syntax lets me search within A and B's X folder so I'm close!

ag foo */X

So the question is essentially: How can I have an arbitrary number of forward slashes (0, 1, or more)?


Solution

  • Simple ag command is not enough

    I don't think this simply just via ag (The silver searcher) command only. You need to somehow filter the input files from the whole directory tree, filtered based on X directory name.

    I would do something along these lines:

    ag 'search\sstring'  `tree -dfi | ag '\/X.*'`  | less
    

    What it does?

    The command in:

    `
    

    is executed and the output is then searched via ag.

    1. filter directories tree -dfi ... prints the whole path (dir and files) you want to search
    • -d ... prints only directories
    • -f ... prints full path prefix for each file
    • -i ... skips spaces in the output (tries to be as processable as possible)

    ag '\/X.*' ... searches for the directory /X within the path (followed by any character present 0 or many times) - use any regexp which will select the directory you want to search in.

    1. search for a text within files

    ag 'search\sstring' ... searches for the 'search string' string within the filtered path

    less is there for you to have searchable output (you can redirect any way you want)