Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

I am writing a program on the pi using wc -m command to count the amount of letters in a string, however, it counts the letters but adds one extra. This is what I currently have.

echo "enter a word"
read var1
echo $var1 | wc -c

When I enter the word, it successfully does something, however, for example if I enter "test" it will output 5. Why is it doing this and is there a fix? Thanks

share|improve this question

1 Answer 1

up vote 1 down vote accepted

This has to do with the command you're using to pipe the string to wc. The echo command is slipping in an extra character at the end of your string, test, a new newline character, \n.

So in effect you're counting this: test\n. You can disable this behavior with the -n switch to echo.

$ echo -n "test" | wc -c
4

Or use a different command to generate your string, such as printf:

$ printf "%s" "test" | wc -c
4

Seeing what's happening

You can use od to see the actual characters that are getitng passed to the pipe like so:

$ echo "test" | od -c
0000000   t   e   s   t  \n
0000005

$ echo -n "test" | od -c
0000000   t   e   s   t
0000004
share|improve this answer

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.