Get the number of spaces characters in a string?

A straightforward way would be to select just the first line, drop non-witespace characters from it, and count how many characters are left:

head -n 1 | tr -cd ' \t' | wc -c

You can use GNU sed to replace the head|tr combo (here assuming POSIXLY_CORRECT is not in the environment):

sed '1s/[^ \t]//g' |wc -c

Note: sed will always print out a newline, so the count you'll will include the newline itself. How this works: In sed, you can give the s/// command an address range, which here is just the first line. Globally replace any non-whitespace with nul and output the result to wc which counts characters.

It's possible, but ugly, to figure out a pure-sed version which does the counting.

A perl version is also simple enough:

perl -lne 's/[^ \t]//g;print length($_);last'

The principle is the same. The -l option outputs a trailing newline. The -n option wraps the script in a giant while-readline loop. And last terminates that loop.

Stéphane's awk solution reminded me you can do that also with perl:

perl -lne 'print s/[[:space:]]]//g;last'

Or replace it with [[:blank:]] to include the newline and other non-printing characters.


awk '{print gsub("[ \t]",""); exit}' < file

Or to count any blank (horizontal spacing characters), not just space and tab:

awk '{print gsub("[[:blank:]]",""); exit}' < file