3

I wanted to count the number of whitespace characters in a file. The best I could come up with was:

tr -cd [:space:] < my_file | wc

Is there a neater way?

  • Do you want to count newlines as well ? – 123 Jun 29 '15 at 14:03
  • @User112638726 yes please – Armand Jun 29 '15 at 14:04
  • Also what exactly do you mean by neater ? – 123 Jun 29 '15 at 14:07
  • @User112638726 e.g. just counting the characters. my solution deletes everything else and then counts what's left - seems a bit indirect to me – Armand Jun 29 '15 at 14:10
  • 3
    @Alison - your method might seem indirect, but I don't think that's the case. No matter how you do this task, you have to have a program that examines every character (every byte) in the file. There's no short cuts for that I can see. "Deleting" isn't really the case, as tr actually just passes all whitespace characters down the pipe. It's just selective about what characters it passes, rather than "deleting" anything. – Bruce Ediger Jun 29 '15 at 16:40
3
tr -cd '[:space:]' < my_file | wc -m

Would work. But with GNU tr, that would only work in single byte per character locales (typically, not in UTF-8 ones) or with ASCII only input in UTF-8 locales.

Without the quotes around [:space:], you'd get an error message in csh, tcsh or zsh (unless the condition below is met) and in most shells, that would fail if there was a file called :, s, p, a, c or e in the current directory as [:space:] is a shell glob.

Also note that wc doesn't count characters by default (it's bytes, words and newlines only when not given any option).

With GNU awk you can use:

awk -v RS='[[:space:]]' 'END{print NR}'

Example:

$ printf '\0\u2006\t\r\n' | awk -v RS='[[:space:]]' 'END{print NR}'
4
0
#!/bin/bash

file=`cat $1`

length=`cat $1 | wc -m` // Count the charater
count=0
for ((i = 0 ;i < $length;i++)) do //loop to the end of the string

    if [ "${file:$i:1}" == "$2" ] //Look only character by character (select some characters of the String, (:$i:1) is the range of the choosen characters
    then
        count=$((count + 1))

    fi
done    
echo $count

//test.txt = "Is there a neater way?"
#./CountChar test.txt " "
>>> 4

it's an "other" way..x), hope you like it !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.