How to count all spaces in a file in Unix

Baba picture Baba · Aug 4, 2013 · Viewed 16.4k times · Source

I want to count all the spaces from my file in Unix and I have tried the following command:

grep " " file1 | wc

It is giving me the following output:

3 6 34 

There are three spaces in my file so is it accurate command and further more how can I filter this to get exactly the spaces so only '3' should come as output and also how can I remove it

Answer

hek2mgl picture hek2mgl · Aug 4, 2013

Use grep and wc in a way like this to count the occurrences of spaces:

grep -o ' ' | wc -l 

grep -o will print every match in a separate line. The number of those lines can afterwards counted easily using wc -l