Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count all spaces in a file in Unix

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

like image 710
Baba Avatar asked Aug 04 '13 13:08

Baba


3 Answers

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

like image 74
hek2mgl Avatar answered Nov 15 '22 11:11

hek2mgl


Use tr to remove everything but the spaces, then wc -c to count the remaining (space) characters:

tr -cd ' ' <file1 | wc -c
like image 37
Gordon Davisson Avatar answered Nov 15 '22 09:11

Gordon Davisson


This sed (stream editor) command will remove all the white space in a text file:

sed -e 's/^[ \t]*//' -e 's/[ \t]*$//' yourFile
like image 42
David Elliman Avatar answered Nov 15 '22 09:11

David Elliman