4

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

10

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
    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 '11 at 6:09
11

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
  • also printf "hello" vs printf "hello\n" – Aaron Mar 13 '17 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 '17 at 19:59
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.