in tmp
I type a single character,but wc -c
shows 2
,why?
3 Answers
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.
-
2as a workaround, you could count newlines with
wc -l
and substract them from the count ofwc -c
. If you are counting directly from a piped / redirected output, consider using tee for splitting it. Jul 6, 2011 at 6:09 -
If the character count provided by wc -c
is +1 more than expected, its input likely contains a newline \n
character.
One way to handle this is to use 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
Note that the examples above use echo
, which adds the newline \n
character.
-
1
-
@Aaron makes a great point. If you're able to use printf instead of echo, you eliminate the newlines altogether. The echo command adds a newline character.– EmeraldoMar 16, 2017 at 19:59
-
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