Read the total number of matches in the directory with ag

I am trying to find the number of matches for a given string in a large project. Currently, I use the following command to do this with ag :

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

which is obviously a little long and not very intuitive. Is there a better way to get the total number of matches in a directory from ag ? I broke through the documentation and did not find anything useful.

Edit: thanks to the recent fix before ag file names can be removed using ag instead of sed , so this also works:

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

Note: I understand that I can do this with ack -hcl searchterm (well, almost. In my specific case I will need --ignore-dir building ), but since this is already a big project (and will increase significantly), speedup, the proposed ag makes it preferable ( ack takes about 3 seconds for my searches vs ag almost instant results), so I would stick with it.

+5
source share
2 answers

I use ag to match statistics. For instance:

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

View filter to print the total number of matches:

  >$ ag --stats --java -c 'searchstring' | ag -o '^[0-9]+(?=\smatches)' >$ 22 
+7
source

There is still no great solution, but here is what I managed to come up with for those who found this:

If you are not looking for a huge number of files, just use ack -hcl searchterm , otherwise ...

I managed to improve the command in my question using the --stats , which adds something like the following to the search results:

 714 matches 130 files contained matches 300 files searched 123968435 bytes searched 0.126203 seconds 

For manual use, this is good enough (although it still floods the screen with all the matches), but for scripts, I still only need a number. So, for this purpose, I moved from the command in my question to this:

 $ ag --stats searchterm | tail -n5 | head -n1 | cut -d" " -f1 

or more concise but less memorable

 $ ag --stats searchterm | tac | awk 'NR==5 {print $1}' 

(replace tac with tail -r if you don't have tac )

To save a little more input, I smoothed out the second half of the command, so I can just pass ag --stats to my alias and get what I want. So, with alias agmatches='tac | awk "NR==5 {print \$1}' alias agmatches='tac | awk "NR==5 {print \$1}' I can only get matches by running ag --stats searchterm | agmatches .

It would still be much better if it were something built into ag to help this. I sent a transfer request for the output option --stats-only , which would help , but none of this was there yet , which is available if you create directly from the repo, but not yet in a stable release, so this should speed up the process tidbit for lots of results.

+2
source

All Articles