1

I have a file (see below), and I would like to count the number of 1's and of 0's:

1
1
1
0
0
1
1
0
0
0
...

I tried to use awk but it doesn't work, for example, to count the number of 1's:

awk -F "1\n" '{print NF-1}'

How shall I do it?

I assume the file only contains 1's and 0's, and each line is just a single number. But I more like to know how to generalize to the case for counting the occurrences of a specific line in a file.

5

This counts the number of ones and zeros in filename:

$ sort <filename | uniq -c
      5 0
      5 1
|improve this answer|||||
3

With awk:

awk '/0/{zero++} /1/{one++} END{printf "0: %d\n1: %d\n", zero, one}' filename

With grep, needing two commands:

grep -c 1 filename
grep -c 0 filename

For a string that covers the entire line:

grep -cFx 'target string' filename

Presumably your string might contain characters that have special meaning in regex, so we need to use -F. -x specifies that the whole line must match.

With awk:

awk '$0 == "target string" {count++} END {print count}'
|improve this answer|||||
  • Thanks. Could you generalize to the case for counting the occurrences of a specific line (not part of a line) in a file? – Tim Apr 22 '15 at 18:20
  • @Tim the target string should cover the entire line? – muru Apr 22 '15 at 18:21
  • 1
    @Tim see updates. – muru Apr 22 '15 at 18:24
1

Delete everything but 0 and print the character counts:

tr -cd 0 < file | wc -m

Output:

5
|improve this answer|||||
1

Another possibility is to grep for lines matching exact "0" (or "1") and count the resulting lines:

grep "^0$" filename | wc -l

=> 5

grep "^1$" filename | wc -l

=> 5

Or count both alternatives in a single grep:

grep "^[01]$" filename | wc -l

=> 10

|improve this answer|||||
1

Ed, man! !man ed:

$ ed -s file <<EOT
g/0/d
n
u
g/1/d
n
EOT

13  1
17  0
|improve this answer|||||
  • This won't work OK if lines not matching 0 or 1 are present in the file. If you want to avoid that and still emulate the sort | uniq -c behavior you'll have to use v instead of g e.g. v/^0$/d .... – don_crissti Apr 22 '15 at 22:07
  • @don_crissti that's correct. This obviously also have problems when the file is empty or doesn't contain any 0 or 1s. – FloHimself Apr 23 '15 at 6:24
1
perl -n0E 'say tr/0//, "+",tr/1//'

or following OP tentative:

awk -v RS=1 'END{print NR-1}'
|improve this answer|||||

Not the answer you're looking for? Browse other questions tagged or ask your own question.