Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I 'grep -c' and avoid printing files with zero '0' count

Tags:

grep

The command 'grep -c blah *' lists all the files, like below.

 % grep -c jill *
 file1:1
 file2:0
 file3:0
 file4:0
 file5:0
 file6:1
 % 

What I want is:

 % grep -c jill * | grep -v ':0'
 file1:1
 file6:1
 % 

Instead of piping and grep'ing the output like above, is there a flag to suppress listing files with 0 counts?

SJ

like image 436
San Jose Avatar asked Feb 22 '16 22:02

San Jose


People also ask

How can I grep without printing?

To suppress the default grep output and print only the names of files containing the matched pattern, use the -l ( or --files-with-matches ) option.

How do you negate in grep?

To use negative matching in grep , you should execute the command with the -v or --invert-match flags. This will print only the lines that don't match the pattern given.

How do I ignore a grep file?

By default, grep is case-sensitive. This means that the uppercase and lowercase characters are treated as distinct. To ignore the case when searching, invoke grep with the -i option. If the search string includes spaces, you need to enclose it in single or double quotation marks.

How do you make grep ignore case?

Grep Case Insensitive with -i Option The case insensitive search can be made with the -i option for the grep command. The search pattern “LINUX” matches with “Linux”, “LiNux” or “LinuX” for the case insensitive search.


2 Answers

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 (thanks @CraigEstey).
  • 'string' your string goes here.
  • . Start from the current directory.
  • | grep -v ':0$' Remove 0-count files. (thanks @LaurentiuRoescu)

(I realize the OP was excluding the pipe trick, but this is what works for me.)

like image 124
Bob Stein Avatar answered Oct 05 '22 07:10

Bob Stein


Just use awk. e.g. with GNU awk for ENDFILE:

awk '/jill/{c++} ENDFILE{if (c) print FILENAME":"c; c=0}' *
like image 23
Ed Morton Avatar answered Oct 05 '22 07:10

Ed Morton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!