linux Asked: 2011-07-06 21:58:15 +0800 CST2011-07-06 21:58:15 +0800 CST 2011-07-06 21:58:15 +0800 CST Why `wc -c` always count 1 more character? 772 in tmp I type a single character,but wc -c shows 2,why? command-line-interface 3 Answers Voted Emeraldo 2012-11-02T12:02:10+08:002012-11-02T12:02:10+08:00 One way is to tr to delete newlines, then you can count the characters. Standard behavior: echo HELLO | wc -m # result: 6 echo -n HELLO | wc -m # result: 5 To show the count of newline characters found: echo HELLO | wc -l # result: 1 echo -n HELLO | wc -l # result: 0 Strip the newline character and count characters: echo HELLO | tr -d '\n' | wc -m # result: 5 Strip the newline character (and possible returns with \r) and count characters for an input file: tr -d '\n\r' < input.txt | wc -m Best Answer Ignacio Vazquez-Abrams 2011-07-06T22:00:23+08:002011-07-06T22:00:23+08:00 Because newlines are characters too. Tell your text editor to not add one at the end of the file. No, I don't know how. dragon788 2017-03-13T14:17:17+08:002017-03-13T14:17:17+08:00 I've been using a similar suggestion to the-wabbit's for my calculations. as a workaround, you could count newlines with wc -l and substract them from the count of wc -c. function num_chars () { # echo -e tells echo to honor certain sequences like \n chars=$(echo -e "${1}" | wc -c) lines=$(echo -e "${1}" | wc -l) real_chars=$(echo "$chars - $lines" | bc) echo "$real_chars" } num_chars "hello Dolly" 11 #Result num_chars "hello dolly" 11 #Result num_chars "hello \nDolly" 11 #Result
One way is to
tr
to delete newlines, then you can count the characters.Standard behavior:
To show the count of newline characters found:
Strip the newline character and count characters:
Strip the newline character (and possible returns with
\r
) and count characters for an input file:Because newlines are characters too. Tell your text editor to not add one at the end of the file. No, I don't know how.
I've been using a similar suggestion to the-wabbit's for my calculations.