Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count total number of matches in directory with ag

I'm attempting to find the number of matches for a given string across a large project. Currently, to do this with ag I am using the following command:

$ echo 0$(ag -c searchterm | sed -e "s/^.*:/+/") | bc

which is obviously a bit lengthy and not very intuitive. Is there any better way to get the total number of matches in a directory from ag? I've dug through the documentation and couldn't find anything helpful there.

Edit: Thanks to a recent commit to ag, the filenames can be stripped with ag instead of sed, so this also works:

$ echo `ag test -c --nofilename | sed "s/$/+/"`0 | bc

Note: I realize I could do this with ack -hcl searchterm (Well, almost. In my specific case I'd need an --ignore-dir building in there as well), but as this is already a large project (and will be growing considerably), the speed boost offered by ag makes it preferable (ack takes about 3 seconds for my searches vs ag's nearly instantaneous result), so I would like to stick with it.

like image 276
SnoringFrog Avatar asked Aug 13 '15 18:08

SnoringFrog


1 Answers

I use ag itself to match the stats. E.g.:

 >$ ag --stats --java -c 'searchstring' | ag '.*matches'
 >$ 22 matches 
 >$ 6 files contained matches

Filter with lookahead to print just the number of matches:

 >$ ag --stats --java -c 'searchstring' | ag -o '^[0-9]+(?=\smatches)'
 >$ 22   
like image 164
gregory Avatar answered Sep 21 '22 14:09

gregory