Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
the -c option is a byte count, not a character count – mcalex Dec 30 '12 at 9:34
-m, --chars print the character counts I also used this same problem – user1865719 Dec 30 '12 at 9:36
You're right, I thought unicode was two bytes per char, but it seems ascii letters in uni are still 1 byte. Curious. I'm thinking EOL – mcalex Dec 30 '12 at 9:41
yes, I typed "k" in a file and it shows 2 chars i removed it , so it shows 0 curious – user1865719 Dec 30 '12 at 9:43
up vote 8 down vote accepted

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.

share|improve this answer
ok, so there's one word and one line, but OP wants to know why there are two characters/bytes – mcalex Dec 30 '12 at 9:40
I want to count number of characters not words nor lines – user1865719 Dec 30 '12 at 9:41
ahhh, so you mean echo -n "k" | wc -c. That makes sense – mcalex Dec 30 '12 at 9:46
I put the char in file and it gives so that the EOF counted? or new line or what?, As I want to count more than one char – user1865719 Dec 30 '12 at 9:46
It worked whit -n but why explain please – user1865719 Dec 30 '12 at 9:47

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

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
share|improve this answer

It's because you are using echo (which has a carriage return), instead use printf:

$ echo k | wc -c 2

$ printf k | wc -c 1
share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .