pythonlinuxbashgrepripgrep

Grep summary with file name only once


I am trying to figure out a way to summarize the grep results and show results with filename once instead of every line. I know that ripgrep has this feature. I went through grep man page but couldnt find anything similar.

I have a python script that process results of ripgrep. Looking to reuse the same script for grep if i can get the similar results

Any suggestions on how we can implement that.

current grep output

\grep  -r "else" .                                                                                                                                             
./historyChecker.py:        else:
./historyChecker.py:    else:
./historyChecker.py:    else:
./historyChecker.py:    else:

output that I would like to get

historyChecker.py
77:#check if RG is installed else exit
84:        else:
102:    else:
148:    else:
225:    else:

Solution

  • grep doesn't have an option to do this, so you'll need to print the filenames yourself in a loop.

    find . -type f | while read -r filename; do
        if grep -q "else" "$filename"; then 
            echo "$filename"
            grep -n "else" "$filename"
        fi
    done
    

    Unfortunately this needs to read each file twice: first to check if there's a match so it will print the filename, then to print all the matches. An alternative would be to write the grep output to a temp file, then check if the file is non-empty and print it preceded by $filename.