Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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
3  
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
add comment

2 Answers

up vote 3 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
show 5 more comments

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

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.