计算每行文本出现次数

bas*_*ero 5 grep text-processing

我必须解析某些行感兴趣而其他行不感兴趣的巨大文本文件。在那些感兴趣的人中,我必须计算某个关键字的出现次数。

假设文件被调用input.txt,它看起来像这样:

format300,format250,format300
format250,ignore,format160,format300,format300
format250,format250,format300
Run Code Online (Sandbox Code Playgroud)

我想排除行ignore并计算 的数量format300,我该怎么做?

到目前为止,我得到的是这个命令,它只计算每行一次(这还不够好):

cat input.txt | grep -v ignore | grep 'format300' | wc -l

有什么建议?如果可能,我想避免使用 perl。

Mel*_*lan 9

这个单线应该能够做你想做的:

grep -v ignore input.txt | sed 's/format300/format300\n/g' | grep -c "format300"
Run Code Online (Sandbox Code Playgroud)

基本上,您正在用关键字本身和换行符替换每次出现的关键字,这有效地使您的输入流在任何给定行中只包含一次关键字。然后grep -c是计算其中包含关键字的行数。

  • 我会将 `sed` 替换为 `tr',''\n'` 否则你将计算 `format3000`s 以及不只是 `format300`s (3认同)
  • @1_CR,同意,但您还必须使用 `grep -xc format300` 而不是 `grep -c format300` 以避免误报“format3000”。所以完整的解决方案是`grep -v ignore input.txt | tr , '\n' | grep -xc format300` (2认同)

Car*_*rós 7

您不需要第一个cat,它被称为cat (UUOC)无用使用

此外,非常有用的是grep -o,它只输出匹配的模式,每行一个。

然后,用 计算行数wc -l

grep -v ignore YOUR_FILE | grep -o format300 | wc -l
Run Code Online (Sandbox Code Playgroud)

3为您的小样本打印。