Search code examples
terminalgrepfile-search

Grep - showing current directory/file in a recursive search


The problem

Sometimes, when I run the grep tool recursively it gets stuck in some big directories or in some big files, and I would like to see the directory or file name because perhaps I may realise I don't need to scan that specific directory/file the next time I use grep for a similar purpose, therefore excluding it with the corresponding grep options.

Is there a way to tell grep the current path directory/file which is being scanned in such searches?

My attempts

I tried to search here but it's impossible to find something since usually the keywords current directory are used for other reasons, so there is a conflicting terminology.

I have also tried things like:

man grep | grep -i current
man grep | grep -i status

(and many others) without success so far.

EDIT: I have just found a useful answer here which is for a different problem, but I guess that it may work if I modify the following code by adding an echo command somewhere in the for loop, although I have also just realised it requires bash 4 and sadly I have bash 3.

# Requires bash 4 and Gnu grep
shopt -s globstar
files=(**)
total=${#files[@]}
for ((i=0; i<total; i+=100)); do
  echo $i/$total >>/dev/stderr
  grep -d skip -e "$pattern" "${files[@]:i:100}" >>results.txt
done

Solution

  • find . -type f -exec echo grepping {} \; -exec time grep pattern {} \; 2>&1

    • find . -type f to find all the files recursively.
    • -exec echo grepping {} to call out each file
    • -exec time grep ... {} to report the time each grep takes
    • 2>&1 to get time's stderr onto stdout.

    This doesn't report a total time per directory. Doing that this way either requires more advanced find, to find leaf dirs for grep -d, or to add some cumulative time per path, which I'd do with perl -p... but that's nontrivial as well.