AWK问题:计算“不匹配”

布拉吉什

我想计算文件中某些单词的出现次数。然后,我修改我的代码以另外计算与任何单词不匹配的行数。

例如,这是我的输入文件(test.txt):

fred
fred
fred
bob
bob
john
BILL
BILL

这是我的代码:

awk '
    /fred/ { count["fred"]++ }
    /bob/ { count["bob"]++ }
    /john/ { count["john"]++ }
   END      { for (name in count) print name, "was found on", count[name], "lines." }
   ' test.txt

这工作正常,并提供以下输出:

john was found on 1 lines.
bob was found on 2 lines.
fred was found on 3 lines.

现在,我想对不匹配的行进行计数,因此我执行了以下代码:

awk '
    found=0
    /fred/ { count["fred"]++; found=1 }
    /bob/ { count["bob"]++; found=1 }
    /john/ { count["john"]++; found=1 }
    if (found==0) { count["none"]++ }
   END      { for (name in count) print name, "was found on", count[name], "lines." }
   ' test.txt

我在这样的if语句上收到错误:

awk: syntax error at source line 6
 context is
        >>>  if <<<  (found==0) { count["none"]++; }
awk: bailing out at source line 8

任何想法为什么这不起作用?

比那

您有关于使用条件的简单语法错误。该语句无效:

awk 'if (found==0) { count["none"]++ }'  # syntax error

因为if ()它不会构成可能在外部存在的条件{}您应该使用以下任一方法:

awk '{ if (found==0) count["none"]++ }'

要么

awk 'found==0{ count["none"]++ }'

同样found = 0,脚本的开头应该放在里面,{}因为它也是一条语句。这里有一些有用的链接:{}可以在这些模式的外部和前面,而在内部{}操作


仅需进行必要修改的脚本可以是:

BEGIN { count["fred"]; count["bob"]; count["john"]; count["none"] }
{ found = 0 }
/fred/ { count["fred"]++; found=1 }
/bob/ { count["bob"]++; found=1 }
/john/ { count["john"]++; found=1 }
found==0{ count["none"]++ }
END { for (name in count) print name, "was found on", count[name]+0, "lines." }
  • 纠正了两个语法错误。
  • 添加了项目初始化,因为如果没有它,则如果根本没有“ fred”,则不会为“ fred”打印任何行。
  • 添加,count[name]+0因此,如果item为空字符串,将打印零。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章