Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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:
robin
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

2 Answers 2

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

len=${#str}
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 at 1:10

Your Answer

 
discard

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.