1

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)?

veeTrain
  • 2,915
  • 2
  • 26
  • 43

1 Answers1

1

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)

tukan
  • 17,050
  • 1
  • 20
  • 48
  • 1
    I love this answer. Thank you for the effort you put into it! It makes sense and once I `sudo apt install tree`, I saw exactly what I wanted. Really great job making this as easy to understand as possible. Piping to less was unnecessary but I may still use that sometimes. Thanks again! – veeTrain May 26 '22 at 13:24
  • May require some massaging for working in a windows environment where `ag` works but `tree` is not as easy to use from what it appears. Glad I have the flexibility for both! – veeTrain May 26 '22 at 14:11
  • 1
    @veeTrain you are welcome. On WindowsI would use `MSYS2`. Other option would be cygwin or WLS2. – tukan May 26 '22 at 17:32