Not really a blog, just some stuff that a future me might need to remember one day.
Ag is a file search tool and is a drop-in replacement for Ack.
It is fast and is designed for programmers who need a simple find in
files function. I mostly use it in Vim using the Ag.vim plugin but it’s
a program that you can run from the command line. The examples below
just use ag
from the command-line but if you have Ag.vim you can
substitute ag
for Ag
at the Vim command prompt to perform the same
search.
It works pretty well out of the box but there are a few configuration options and command-line switches that make it even more useful so it’s worth getting to know a few tricks.
To keep you searches fast and focused you’ll probably want ag to ignore
certain files, file types and directories. By default the contents of
your .gitignore
will be excluded from any searches but you might want
to customise this further. You can create a .agignore
file in your
home directory and add file and directory patterns.
For example:
log/*
*.obj
tmp/*
tags
Excludes everything in the log
and tmp
directories as well as all
files with the .obj
extension (in any directory) and your ctags file.
Certain patterns that work in .gitignore
don’t work in .agignore
however. For example, neither **/*.log
and log/*.log
match
log/test.log
.
Its also worth bearing in mind that ag
doesn’t pick up .gitignore
from
a parent directory so if you are doing a search from a sub-directory of
your project root you can’t rely on .gitignore
to exclude unwanted
search paths whereas .agignore
is always picked up form your home
directory.
Sometimes you want to limit your search to a certain kind of file, maybe you know what you are looking for is in a Ruby file.
Common file types are built into ag. You can check the file types that
ag knows about with the --list-file-types
option:
$ ag --list-file-types
...
--ruby
.rb .rhtml .rjs .rxml .erb .rake .spec
...
--yaml
.yaml .yml
Ag just uses the file extension to work out what the type of each file
is. You can see that because Ruby is commonly embedded in .erb
files
ag considers such files to be Ruby type files.
To search for foobar
in Ruby files:
$ ag --ruby foobar
or in JavaScript files:
$ ag --js foobar
Search expressions can be regular expressions as well as plain strings but you might need to quote those:
$ ag 'person|people'
There are several command-line options, a few that I find most useful are:
-w
for whole word matching-i
for case-insensitive matching-s
for case-sensitive matching-l
to just list files containing matches without contentIf you want to narrow your search to a specific directory and it’s sub-directories it’s pretty straightforward to pass a path as a second argument:
$ ag foobar path/to/foo
or to search in all .rb
and .js
files under a certain path:
$ ag foobar path/to/**/*.(rb|js)