简体   繁体   English

仅在匹配项大于 3 时才进行 awk 打印,如果小于 3 则不打印

[英]Make awk print only if matches are greater than 3 and not print if less than 3

How can I make awk print only if it matches 3 or more and NOT print if it's less than 3.如何仅在匹配 3 个或更多时才进行 awk 打印,如果小于 3 则不打印。

I'm not strong in awk programming.我不擅长 awk 编程。 But here is what I tried.但这是我尝试过的。

    awk '/DEF/ {count++;print} { if ( count >  2 ) print count  } ' file
    DEF

DEF is the result from the command above. DEF是上述命令的结果。 It is not suppose to print because there is only one match in the file, not 3 or more.不应该打印,因为文件中只有一个匹配项,而不是 3 个或更多。

The pattern DEF is in the file once, but awk still prints it even though I wrote in the if statement to print only if it matches 3 or more.模式 DEF 曾经在文件中,但即使我在 if 语句中写了仅当它匹配 3 个或更多时才打印,awk 仍然打印它。 Any ideas what I am doing wrong?任何想法我做错了什么?

This will print number of line with DEF found in the file more than 2 times (3 or more):这将打印在文件中找到的带有DEF的行数超过 2 次(3 次或更多):

awk '/DEF/ {++c} END {if (c>2) print c}' file

What if there are two DEF on one line, count as one line or two DEF ?如果一行有两个DEF ,算作一行还是两个DEF呢?

Print the lines found when there are more than two DEF lines found.当找到两个以上的DEF行时打印找到的行。

awk '/DEF/ {++c;a[NR]=$0} END {if (c>2) {for (i in a) print a[i]}}' file

This will print a line with number of DEF lines found as well as the line.这将打印一行,其中包含找到的DEF行数以及该行。

awk '/DEF/ {++c;a[NR]=$0} END {if (c>2) {print "DEF found "c" times";for (i in a) print a[i]}}' file

This will print number of hits and line number its found in as well:这将打印命中数和找到的行号:

awk '/DEF/ {++c;a[NR]=$0} END {if (c>2) {print "DEF found "c" times\n-----";for (i in a) {print ++t". line "i": "a[i]}}}' file
DEF found 3 times
-----
1. line 4: DEF first time
2. line 8: red DEF second time
3. line 16: DEF more

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM