在Unix中命令计算特定单词的出现次数

时间:2013-04-04 06:47:13

标签: unix

我想在Unix中搜索Exact word pattern,

示例:Log.txt文件包含以下文本:

aaa         (only this 'aaa' pattern shhold be counted)
bbb
cccaaa   ---> this should not be counted in grep output
ccc_aaa   --> this should not be counted in grep output
ccc-aaa   --> this should not be counted in grep output
ccc.aaa   ---> this should not be counted in grep output

我正在使用以下代码 -

count=$?
count=$(grep -c -w aaa $ZZZ\Log.txt)

此处输出应为==> 1但是我得到4作为输出,我想,有些东西不见了所以,有人可以帮我这个吗?

2 个答案:

答案 0 :(得分:1)

我相信您正在寻找-x选项。以下是手册页的摘录,它总是找到选项解决方案的最快方法。

-x, --line-regexp
          Select  only  those  matches  that exactly match the whole line.
          (-x is specified by POSIX.)

答案 1 :(得分:0)

给定样本输入,我希望输出为3.对于您期望的行,一行为ccc-aaa,一行为ccc.aaa。 grep文档清楚地指出单词字符是字母,数字和下划线。如果您想将.-视为字构成字符,只需预先过滤数据:

count=$( tr < $ZZZ/Log.txt .- ' '  | grep -c -w aaa )

上述内容使用tr.-的出现次数转换为空格。您可能希望根据需要扩展您要考虑的字符集。

相关问题