I am trying to get the word count of a string using the wc command. But it gives me a different answer. It increases the number of words by 1.

This is the code:

echo Enter a string:
read str
len=`echo $str | wc -c`
echo you have entered: $str
echo and the word count: $len

The output is like this:

Enter a string:
you have entered: robin
and word count: 6

What am I doing wrong? Please help me solve this. I will be very grateful. Thank you.


Assuming you mean character count not word count (which would be 1), the issue is that echo adds a newline character. You can either use

len=`echo -n $str | wc -c`

(the -n switch suppresses the newline) or - better - just use the bash # variable length operator


From man wc:

-c, --bytes
    print the byte counts

-w, --words
    print the word counts

So, you should use wc -w instead of wc -c.

  • You're right, but his question is confusing. I thought he accidently had mistaken -c for count. – Louis Matthijssen Apr 26 '14 at 1:10

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.