Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
up vote 10 down vote accepted

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

share|improve this answer

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.

share|improve this answer
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 posting your answer, you agree to the privacy policy and terms of service.

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