命令计算整个文件中单词的出现次数 [英] command to count occurrences of word in entire file

查看:79
本文介绍了命令计算整个文件中单词的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试计算文件中单词的出现次数.

I am trying to count the occurrences of a word in a file.

如果单词在一行中出现多次,我将计算为1.

If word occurs multiple times in a line, I will count is a 1.

以下命令将给我输出,但是如果一行中多次出现单词,则会失败

Following command will give me the output but will fail if line has multiple occurrences of word

grep -c "word" filename.txt

有一个班轮吗?

推荐答案

您可以使用grep -o显示确切的匹配项,然后对它们进行计数:

You can use grep -o to show the exact matches and then count them:

grep -o "word" filename.txt | wc -l

测试

$ cat a
hello hello how are you
hello i am fine
but
this is another hello

$ grep -c "hello" a    # Normal `grep -c` fails
3

$ grep -o "hello" a 
hello
hello
hello
hello
$ grep -o "hello" a | wc -l   # grep -o solves it!
4

这篇关于命令计算整个文件中单词的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆