grep how to suppress display of non-matched file?

I am trying to find files containing a specific word using grep. There are many files in the directory (> 500)

Command I run

$ grep 'delete' *

Output

validate_data_stage1:0
validate_data_stage2:0
validate_data_stage3:0
validate_data_stage4:0
validate_data_stage5:0
validate_input_stage1:0
validate_input_stage2:0
validate_input_stage3:0
validate_input_stage4:0
.... and hundred of such lines

These are the files that don’t contain the given match. I want to suppress those lines from displaying to stdout. I know of -q switch, but that would suppress the complete output, which I don’t want.

How do I do that?

Asked By: mtk

||

Add

| grep -v ':0$'

Not very elegant but I think will do the job.

Adding -l to your command will give you only matches but it will also suppress printing number of matches for each file.

Answered By: Laurentiu Roescu

Using grep -l you will only get the files that contain at least one match.

Do you need information about how many matches there are in a file at all? Because the you could skip using -c which is used to count the number of matches in a file.

edit: And like warlock said using -I to suppress matches in binary files could also be a good idea.

Answered By: tongpu

That’s the behavior exhibited by grep -c.

Probably you have a file whose name starts with - and contains a c character and you’re using GNU grep without setting the POSIXLY_CORRECT environment variable.

Use:

grep -- delete *

or better:

grep delete ./*

-- marks the end of options so that that filename will not be considered as an option (with a POSIX grep, it wouldn’t since the non-option delete argument would have marked the end of options), but it wouldn’t address the problem of a file called -. The grep delete ./* is more robust but has the drawback of outputting the extra ./ for matching files (though that may be considered a bonus since that helps identify file names that contain newline characters).

Answered By: Stéphane Chazelas

How to grep nonzero counts:

grep -rIcH 'string' . | grep -v ':0$'

  • -r Recurse subdirectories.
  • -I Ignore binary files (thanks @tongpu, warlock).
  • -c Show count of matches. Annoyingly, includes 0-count files.
  • -H Show file name, even if only one file.
  • 'string' your string goes here.
  • . Start from the current directory.
  • | -v ':0$' Remove 0-count files. (thanks @LaurentiuRoescu)

(I realize the OP was unintentionally -c counting, but google(grep nonzero count) lands here.)

Answered By: Bob Stein

Similar to Laurentiu’s answer, you can also use the listing of -l as the file inputs for grep :
grep -r "pattern" -c $(grep -rl "pattern")
It allows keeping grep’s coloring, but does the same thing in the background

Answered By: adriel
Categories: Answers Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.