bash 计算终端输出中的行数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12457457/
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
count number of lines in terminal output
提问by roopunk
couldn't find this on SO. I ran the following command in the terminal:
在 SO 上找不到这个。我在终端中运行了以下命令:
>> grep -Rl "curl" ./
and this displays the list of files where the keyword curl occurs. I want to count the number of files. First way I can think of, is to count the number of lines in the output that came in the terminal. How can I do that?
这将显示出现关键字 curl 的文件列表。我想计算文件的数量。我能想到的第一种方法是计算终端中输出的行数。我怎样才能做到这一点?
回答by Jo?o Silva
回答by JelteF
Putting the comment of EaterOfCode here as an answer.
将 EaterOfCode 的评论放在这里作为答案。
grep itself also has the -c flag which just returns the count
grep 本身也有 -c 标志,它只返回计数
So the command and output could look like this.
所以命令和输出可能看起来像这样。
$ grep -Rl "curl" ./ -c
24
EDIT:
编辑:
Although this answer might be shorter and thus might seem better than the accepted answer (that is using wc
). I do not agree with this anymore. I feel like remembering that you can count lines by piping to wc -l
is much more useful as you can use it with other programs than grep
as well.
尽管这个答案可能更短,因此看起来可能比接受的答案(即使用wc
)更好。我不再同意这一点。我觉得记住您可以通过管道计算行数wc -l
更有用,因为您可以将它与其他程序一起使用grep
。
回答by GCS
Piping to 'wc' could be better IF the last line ends with a newline (I know that in this case, it will)
However, if the last line does not end with a newline 'wc -l' gives back a false result.
如果最后一行以换行符结尾,则管道到 'wc' 可能会更好(我知道在这种情况下,它会)
但是,如果最后一行不以换行符结尾,则 'wc -l' 会返回错误结果。
For example:
例如:
$ echo "asd" | wc -l
Will return 1
and
将返回1
并
$ echo -n "asd" | wc -l
Will return 0
将返回 0
So what I often use is grep <anything> -c
所以我经常使用的是 grep <anything> -c
$ echo "asd" | grep "^.*$" -c
1
$ echo -n "asd" | grep "^.*$" -c
1
This is closer to reality than what wc -l
will return.
这比wc -l
将要返回的更接近现实。