如何在Linux或Unix上使用grep计算单词出现次数


想知道一个单词(比如linuxidc或IP地址)在文本文件中出现了多少次吗?在Linux或类Unix系统上可以使用grep命令来实现。

您可以使用grep命令搜索给定模式的字符串,单词,文本和数字。 您可以将-c选项传递给grep命令。 它仅显示每个文件匹配模式的次数。

显示单词linuxidc在名为linuxidc.txt的文件中出现的总次数

语法是:

grep -c string(字符串) filename(文件名)

[linuxidc@localhost www.linuxboy.net]$ grep -c linuxidc linuxidc.txt

示例输出:

2

要使用grep计算名为/etc/passwd root的文件中出现的字总数,请运行:

grep -c root /etc/passwd

要验证运行:

grep --color root /etc/passwd

会话示例:

如何在Linux或Unix上使用grep计算单词出现次数

将-w选项传递给grep以仅选择与指定模式匹配的整个单词或短语:

grep -w root /etc/passwd

或者

grep -c -w root /etc/passwd

在此示例中,仅匹配与root的单词:

grep --color -w '^root' /etc/passwd

grep -c -w '^root' /etc/passwd

只显示匹配的部分。

grep -o 'root' /etc/passwd
grep -c -o 'root' /etc/passwd

会话示例:

如何在Linux或Unix上使用grep计算单词出现次数

linuxboy的RSS地址:https://www.linuxboy.net/rssFeed.aspx

本文永久更新链接地址:https://www.linuxboy.net/Linux/2019-08/160309.htm

相关内容