Why is wc -c printing spaces before the number?

command:

echo "test" | wc -c

results (7 leading spaces):

"       5"

I tested this on my linux box and I don't get the space in front of the five. is this a bug or expected behavior?


Solution 1:

This is by design. You can see how wc pads “tabs” by removing the -c so it drops the first number in alignment with where the others would be.

You can gobble up the white space if you need with another pipe, but you should plan on this if you’re scripting things on macOS and don’t drop a different wc command down. The options are endless

echo "test" | wc -c | xargs
echo "test" | wc -c | tr -d ' '
echo "test" | wc -c | sed 's/ //g'
echo $(echo "test" | wc -c)

Solution 2:

I find this solution to be more portable in various situations, since I really just want the number of "lines" more often than not.

echo "test" | awk 'END{print NR}' which returns 1

This post has additional information on POSIX implementation https://unix.stackexchange.com/a/205910