如何计算文件中的总字数?

Ric*_*ard 19 text-processing wc

我正在寻找一个命令来计算文件中所有单词的数量。例如,如果一个文件是这样的,

today is a 
good day
Run Code Online (Sandbox Code Playgroud)

那么它应该打印5,因为那里有5单词。

slm*_*slm 42

命令wc又名。字数统计可以做到:

$ wc -w <file>
Run Code Online (Sandbox Code Playgroud)

例子

$ cat sample.txt
today is a 
good day


$ wc -w sample.txt
5 sample.txt


# just the number (thanks to Stephane Chazelas' comment)
$ wc -w < sample.txt
5
Run Code Online (Sandbox Code Playgroud)


Mic*_*ant 7

我想出了这个数字:

wc -w [file] | cut -d' ' -f1

5
Run Code Online (Sandbox Code Playgroud)

我也喜欢这种wc -w < [file]方法

最后,为了仅将字数存储在变量中,您可以使用以下内容:

myVar=($(wc -w /path/to/file))
Run Code Online (Sandbox Code Playgroud)

这让您可以优雅地跳过文件名。

  • `wc -w &lt; "$file"` 只是数字。 (14认同)