【发布时间】:2020-09-23 04:52:04
【问题描述】:
我想计算文件中某些单词的出现次数。然后我修改我的代码以额外计算有多少行与任何单词不匹配。
例如这里是我的输入文件(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
任何想法为什么这不起作用?
【问题讨论】:
-
您能否详细解释一下这里的匹配行是什么意思?您的意思是要打印计数为 1 的行吗?请在同一时间确认一次。
-
@Brajesh 你有一个简单的语法错误。语句“
if found==0”不能在 awk 中单独作为条件开始。这是一个应该嵌套在{}中的操作,如下所示:{ if (found==0) do_something }。或者你可以在{}之前有这样的条件:found==0{ do_something}。
标签: if-statement awk syntax