linux shell wc -c count characters +1

I used the command wc -c to count the number of characters but it gives me a wrong number, number of characters plus one as an example:

echo "k" | wc -c 

it gives me 2 characters

so why not 1?


Solution 1:

Take a look at the help message for wc. The -c option prints out the number of characters. The echo command includes a newline character by default. When wc sees the newline it counts it as another character and hence the additional count in your result. You can get around this by using one of the alternatives shown below; -w counts the number of words and -l counts the number of lines.

echo "k" | wc -w 
echo "k" | wc -l

You can pipe the output of wc to awk to get the number of characters excluding the newline characters:

wc <filename> | awk '{print $3-$1}'

The default output of wc with no options prints out the number of newline characters ($1 to awk), number of words and number of characters ($3 to awk) in this order.

Solution 2:

when you echo "k", the echo command appends a newline character to whatever you asked it to print out ("k"). You can use the -n option to disable this:

echo -n k | wc -c
1

For viewing that invisible character, you could dump stream whith od or hd:

echo k | od -t c
0000000   k  \n

echo k | hd
00000000  6b 0a                                             |k.|

echo k | od -t a -A n
   k  nl

Solution 3:

It's because you are using echo, which adds a newline to your string. Use printf instead:

$ echo k | wc -c 
       2
$ printf k | wc -c
       1