How to search source code in ack or ag

ack (command line)

http://beyondgrep.com/

Designed to be a better grep for source code. As such it includes defaults that make a great deal of sense in that context. Firstly you don't have to specify filenames as it assumes you want to start searching at the current directory and by default will recurse down the file tree. It also will ignore .svn and .git folders assuming (usually correctly) that you have no need to search inside them. Its output is also styled to make searching accross source code easier. Most of its arguments are similar to grep so it is instantly familiar. One really handy feature is being able to include or exclude file types using the --java --nophp syntax. It also ignores known backup files and other such redundant files.

For more performance you can also use the almost compatible version of ag "The Silver Searcher" http://geoff.greer.fm/ag/ which for most comparable searches is about 2-5x faster.

There is also another implementation which is similar to ack and ag called ripgrep https://github.com/BurntSushi/ripgrep which depending on your searching needs can yield even more performance over ag.

As with grep because ack looks at every file and depending on your query every byte in every file it can take a very long time to search across large or multiple code bases.

Some examples of searching over a codebase using ack are included below. All searches are run from within the directory you wish to search rather than having to specify the directory. Be sure to check out the documentation for ack. Note that you can generally swap ack with ag if installed for faster results.

  • ack -i arraylist --java Ignore case search for arraylist in java files
  • ack if -A10 -B5 --shell Show 10 lines after and 5 lines before shell scripts with the text if inside

Some timing tests for a directory using ack and ag on a directory with ~115 Gb of files.

du -hs
115G  .

time ack list -A10 -B5 --java
real  0m12.560s
user  0m7.270s
sys   0m3.132s

time ag list -A10 -B5 --java
real  0m6.204s
user  0m0.544s
sys   0m0.930s

Productivity through code search.

Try searchcode server for Free