WC on OSX - Return includes spaces

4.7k views Asked by At

When I run the word count command in OSX terminal like wc -c file.txt I get the below answer that includes spaces padded before the answer. Does anyone know why this happens, or how I can prevent it?

    18000 file.txt

I would expect to get:

18000 file.txt

This occurs using bash or bourne shell.

5

There are 5 answers

0
rici On BEST ANSWER

I suppose it is a way of getting outputs to line up nicely, and as far as I know there is no option to wc which fine tunes the output format.

You could get rid of them pretty easily by piping through sed 's/^ *//', for example.

There may be an even simpler solution, depending on why you want to get rid of them.

0
Thomas Dickey On

The POSIX standard for wc may be read to imply that there are no leading blanks, but does not say that explicitly. Standards are like that.

This is what it says:

By default, the standard output shall contain an entry for each input file of the form:

"%d %d %d %s\n", <newlines>, <words>, <bytes>, <file>

and does not mention the formats for the single-column options such as -c.

A quick check shows me that AIX, OSX, Solaris use a format which specifies the number of digits for the value — to align columns (and differ in the number of digits). HPUX and Linux do not.

So it is just an implementation detail.

0
Steve Summit On

This bugs me every time I write a script that counts lines or characters. I wish that wc were defined not to emit the extra spaces, but it's not, so we're stuck with them.

When I write a script, instead of

nlines=`wc -l $file`

I always say

nlines=`wc -l < $file`

so that wc's output doesn't include the filename, but that doesn't help with the extra spaces. The trick I use next is to add 0 to the number, like this:

nlines=`expr $nlines + 0`      # get rid of trailing spaces
1
Marco Garduño Sánchez On

This works for me:

var=$(cat test.txt|wc -l|sed 's/      //g')
2
Raphaelly On

At least under macOS/bash wc exhibits the behavior of outputting trailing positional TABs.

It can be avoided using expr:

echo -n "some words" | expr $(wc -c) 
>> 10
echo -n "some words" | expr $(wc -w) 
>> 2

Note: The -n prevents echoing a newline character which would count as 1 in wc -c