1

I have a text file consisting of one line with numbers such as 0 100 90 80 0 70 60

I'm trying to determine how many times the number 0 appears alone (in this case, twice).

I tried using this method which accounts for whitespace,

grep -o " 0 " file | wc -l

but it doesn't account for the first "0" since there's no whitespace preceding it.

djl
  • 267
  • 1
  • 3
  • 13
  • Possible duplicate of [Count all occurrences of a string in lots of files with grep](https://stackoverflow.com/questions/371115/count-all-occurrences-of-a-string-in-lots-of-files-with-grep) – Nijikokun Mar 14 '18 at 01:56

3 Answers3

3

grep -ow '0' num.txt | wc -l

-w word match effectively does this to every pattern:

grep -o '\b0\b' file | wc -l

\b is a word boundary.

Interestingly grep -cow doesn't work to count the matches, which frustrates me.

stevesliva
  • 5,351
  • 1
  • 16
  • 39
  • 1
    The combination of `-co` would indeed be a nice feature for this, and doesn't have any obvious other useful interpretation. There is a bug against GNU `grep` for this since many years: https://savannah.gnu.org/bugs/?33080 – tripleee Mar 14 '18 at 06:37
2
grep -Po '(^|\s)0($|\s)' file | wc -l

You just test if there's a whitespace OR the beginning of line before a zero.

iBug
  • 35,554
  • 7
  • 89
  • 134
  • 1
    `-P` is kind of overkill for this, you could articulate a very similar (but actually better!) regex with `grep -E`but of course, `grep -w` is completely standard. – tripleee Mar 14 '18 at 06:25
0

I'm not sure if this is the best way, but you could use xargs with its -n flag in the following manner:

xargs -n1 < file  | grep ^0$ | wc -l
foundling
  • 1,695
  • 1
  • 16
  • 22
  • 2
    You can avoid the [useless use of `wc`](http://www.iki.fi/era/unix/award.html#wc); anything that looks like `grep x | wc -l` can be rewritten `grep -c x`. As a further optimization, `grep -cFx 0` avoids regex entirely, and hence runs faster still. – tripleee Mar 14 '18 at 06:29