F. Röder
F. Röder

Reputation: 31

How to use ag aka the_silver_search to search for directories only?

I like to search for directories only, and the option ag --list-file-types is not helpful with that. The reason to stick to ag is the possibility to pick a file with --path-to-ignore containing patterns to ignore.

An equivalent command would be fd --type d.

Upvotes: 3

Views: 1949

Answers (2)

gregory
gregory

Reputation: 12973

Use the -G argument, and specify a directory name.

For example, if you wanted to search for the word "foobar" in only your Downloads directory:

ag -G "Downloads" foobar

To search inside a nested directory:

ag -G "Downloads/some_directory" foobar 

To search in multiple directories:

ag -G "Downloads|Documents" foobar

Upvotes: 3

n1k31t4
n1k31t4

Reputation: 2874

You can list of all directories, recursively from your working directory, using ag in a chained command:

ag --null -g ./ | xargs -0 dirname | sort -u
  • --null means each ag output is separated by a \000, which allows special characters to be handled by xargs
  • -g means we only search in filenames, not inside the files themselves
  • ./ running in the current working directory
  • | xargs -0 - pipe all the (relative) file paths from ag into xargs, which uses -0 to accept the --null output we get from ag
  • dirname returns just the directory name of each file
  • sort -u we sort the directories returned and deduplicate them. We will have the same directory ones for every file it contains!

You can then pass the output of that list to grep of something fancier, like [fzf][1].

Upvotes: 0

Related Questions