Get the number of spaces characters in a string?
Solution 1
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
Solution 2
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.
Solution 3
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
Related videos on Youtube
Luigi T.
Updated on September 18, 2022Comments
-
Luigi T. over 1 year
How can I check how many white spaces (' ',
\t
) there are in the first line of a file?-
Admin over 8 yearspossible duplicate of stackoverflow.com/questions/8683443/…
-
-
cuonglm over 8 yearsShorter one
perl -nE 'say tr/ \t//; exit'
-
terdon over 8 yearsComments are not for extended discussion; this conversation has been moved to chat.
-
Otheus over 8 yearsRemoved the
q
-
mikeserv over 8 years@BinaryZebra - nah. it wasnt very good. it was too complicated.
-
mikeserv over 8 years@BinaryZebra - i didnt intend it to be impolite, and i sent that before i found you in chat.