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?
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.
printf
is often preferred before echo
when consistency is important. It does not print a newline unless specifically asked, so printf "k" | wc -m
gives 1
, i.e. the number of characters printed. To count characters in the first line of a file, one can do e.g. $(($(head -1 file | wc -m)-1))
(wrap it in $(())
to do shell arithmetic to remove the newline count) or even better: use awk and do awk 'NR==1{print length}' file
.
Commented
Dec 30, 2012 at 15:20
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
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
-c
option is a byte count, not a character count