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
How to count all spaces in a file in Unix
提问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 grep
and wc
in a way like this to count the occurrences of spaces:
以这样的方式使用grep
和wc
来计算空格的出现次数:
grep -o ' ' | wc -l
grep -o
will 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 tr
to remove everything but the spaces, then wc -c
to 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