Refining Searches using Ag
03 Jan 2017I use Ag a lot to search for keywords in Rails Apps. However sometimes a keyword is present so often that I want to refine my search. One example of this is if I want to search for a keyword present only in test files. Ag has a useful -G flag that allows you to do this.
For example say I wanted to search for the keyword “organization” in files that end in spec.rb. I would use:
> Ag organization -G spec.rb$
The -G flag tells Ag to look for the term inside files with names containing spec.rb. It can accept a regex which is what the $ is for. The $ indicates that I want to search in files that end in spec.rb, not just files that have spec.rb somewhere within their names.
Another example is if I am searching for a keyword that includes punctuation marks which happen to be regex characters. For example, I was searching for “.try” and since Ag automatically treats search terms as regexes by default, it will find all terms with any character followed by try, like “retry” in addition to “.try”.
Ag has a literal expression flag -Q to specify that you’re searching for a literal expression not a regex. In order to search for “.try” you would use:
> Ag -Q .try
For more information see Conquering the Command Line, by Mark Bates