13

in tmp I type a single character,but wc -c shows 2,why?

3 Answers 3

18

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.

2
  • 2
    as a workaround, you could count newlines with wc -l and substract them from the count of wc -c. If you are counting directly from a piped / redirected output, consider using tee for splitting it.
    – the-wabbit
    Jul 6, 2011 at 6:09
  • This is a very unhelpful answer. Why is it the accepted answer?
    – Rikki
    Apr 1, 2021 at 23:28
17

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.

3
  • 1
    also printf "hello" vs printf "hello\n"
    – Aaron
    Mar 13, 2017 at 1:04
  • @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.
    – Emeraldo
    Mar 16, 2017 at 19:59
  • echo -n was super useful for me. Thank you!
    – Rikki
    Apr 1, 2021 at 23:28
0

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

You must log in to answer this question.

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