WC on OSX - Return includes spaces

…衆ロ難τιáo~ 提交于 2019-12-08 04:26:23

问题


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.


回答1:


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.




回答2:


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.




回答3:


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




回答4:


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


来源:https://stackoverflow.com/questions/30927590/wc-on-osx-return-includes-spaces

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!