Wednesday, May 8, 2024
10
rated 0 times [  10] [ 0]  / answers: 1 / hits: 6124  / 2 Years ago, sun, september 4, 2022, 11:12:06

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.


More From » command-line

 Answers
7

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}

[#25664] Monday, September 5, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ligdesig

Total Points: 164
Total Questions: 106
Total Answers: 114

Location: Japan
Member since Sat, Jun 6, 2020
4 Years ago
;