bash 如何在Unix中计算文件中的所有空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18043260/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 06:07:47  来源:igfitidea点击:

How to count all spaces in a file in Unix

bashgnu-coreutils

提问by Baba

I want to count all the spaces from my file in Unix and I have tried the following command:

我想在 Unix 中计算我文件中的所有空格,我尝试了以下命令:

grep " " file1 | wc

It is giving me the following output:

它给了我以下输出:

3 6 34 

There are three spaces in my file so is it accurate command and further more how can I filter this to get exactly the spaces so only '3' should come as output and also how can I remove it

我的文件中有三个空格,所以它是准确的命令,更进一步,我如何过滤它以准确获取空格,所以只有“3”应该作为输出出现,以及如何删除它

回答by hek2mgl

Use grepand wcin a way like this to count the occurrences of spaces:

以这样的方式使用grepwc来计算空格的出现次数:

grep -o ' ' | wc -l 

grep -owill print every match in a separate line. The number of those lines can afterwards counted easily using wc -l

grep -o将在单独的行中打印每个匹配项。这些行的数量之后可以很容易地使用wc -l

回答by Gordon Davisson

Use trto remove everything but the spaces, then wc -cto count the remaining (space) characters:

使用tr去除一切,但空格,然后wc -c计算剩余的(空间)的字符:

tr -cd ' ' <file1 | wc -c

回答by David Elliman

This sed (stream editor) command will remove all the white space in a text file:

这个 sed(流编辑器)命令将删除文本文件中的所有空白:

sed -e 's/^[ \t]*//' -e 's/[ \t]*$//' yourFile