LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   wc -c is not working properly for Strings (https://www.linuxquestions.org/questions/linux-newbie-8/wc-c-is-not-working-properly-for-strings-4175614316/)

gursewaks056 09-22-2017 01:28 PM

wc -c is not working properly for Strings
 
When I count the number of character in a string using
`wc -c $Str` it always gives a one character extra to me.
e.g : str="Good" ; len=`echo $str | wc -c`
it results in len=5 not 4.

astrogeek 09-22-2017 01:35 PM

When you echo the string, echo appends a newline character which is counted by wc.

Suppress the newline to do this with echo, or better might be to use the shell's built in operator for getting the string length, ${#var}.

aragorn2101 09-25-2017 04:11 AM

Quote:

Originally Posted by gursewaks056 (Post 5761742)
When I count the number of character in a string using
`wc -c $Str` it always gives a one character extra to me.
e.g : str="Good" ; len=`echo $str | wc -c`
it results in len=5 not 4.

Yes, as astrogeek pointed out, echo adds a newline character at the end, so it increases the count. You can use the "-n" argument with echo in order to suppress the newline character.

But first, I would like to make you notice that wc with argument "-c" will count number of bytes, not number of characters. You are getting the correct number of characters (counting the newline) because every character is 1 byte each. But it will not work with multibyte characters like UTF-8.
Code:

echo -n "Good" | wc -c
4

echo -n "Fête" | wc -c
5

# Whereas, with the argument "-m"
echo -n "Good" | wc -m
4

echo -n "Fête" | wc -m
4

Please read the man pages for wc for more information.


All times are GMT -5. The time now is 10:33 PM.