Baba
Baba

Reputation: 73

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

Upvotes: 6

Views: 21044

Answers (3)

Gordon Davisson
Gordon Davisson

Reputation: 126038

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

tr -cd ' ' <file1 | wc -c

Upvotes: 11

hek2mgl
hek2mgl

Reputation: 158210

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

Upvotes: 19

David Elliman
David Elliman

Reputation: 1399

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

sed -e 's/^[ \t]*//' -e 's/[ \t]*$//' yourFile

Upvotes: 1

Related Questions