wc command prints wrong output character count [Solved]

Updated on August 29, 2023

Question: Why does wc command prints wrong output character count when used with echo command in Linux? Below is the command I used to count the number of characters in a string.

$echo "santhosh" | wc -c
9

But it always gives me one count more. Am I doing anything wrong? Please help me to solve this.

Solution: The issue is not with wc, but with the usage of echo. By default echo command adds a trailing newline character and when piped to wc command, you see one character count more than the actual string length.

To suppress the trailing newline, use -n option for echo command as shown below:

$echo -n "santhosh" | wc -c
8
Note

Bash is the default command shell in nearly every major Linux distribution. So this command has been tested on bash shell.

Was this article helpful?

Related Articles

Leave a Comment