bash - 命令来计算整个文件中单词的出现次数

标签 bash shell grep

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

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

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

grep -c "word" filename.txt

有没有一种类轮?

最佳答案

您可以使用 grep -o 来显示完全匹配,然后计算它们:

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

关于bash - 命令来计算整个文件中单词的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21603555/

相关文章:

bash - 从 Bash 脚本在 PostgreSQL 中创建 FUNCTION

php - 通过 PHP 的 shell_exec() 从网页执行 bash 脚本,这需要其他用户的权限?

linux - 使用 Sed 提取多个文件中的标题

shell - 如何将文本与扩展变量组合成 Fish 中的变量扩展

linux - 如何从 Bash 中的字符串中删除所有非数字字符?

linux - 查找最后一次出现的字符串并在 BASH 中打印 sed awk grep 下面的所有内容

linux - lftp pget ...不打开多线程

linux - 复制文件 - 不是目录

linux - 多个 grep 管道(包含+排除)导致不显示任何内容

linux - 如何使用grep从txt文件中获取大于50的数字