使用awk只打印一次不可用的记录

Using Awk to print the unavailable record only once

我正在编写一个 awk 脚本,里面看起来像这样:

awk -v searchValue="$searchValue" '{ if ( == searchValue){
                                                    printf NR".", , , ,                                           
                                     }
                                     else if (!=searchValue) {print "The value that you entered is not available. Please try again."}                                                                      
                                     }' file

这是我的文件。

One Two 20 100
Three Four 10 500
Five Six 30 800
Seven Eight 20 500

这尝试打印一次 else if 方法,但它打印了所有不包含搜索值的行。 如果我输入 20,我的输出如下所示:

1. One  Two  20 100
The value that you entered is not available. Please try again.
The value that you entered is not available. Please try again.
4. Four Five 20 500

如果输出一次,我必须使用 awk 命令打印 else。比方说,如果我输入 700。我该如何解决它才能得到这个:

The value that you entered is not available. Please try again.

也许是使用 END 子句的解决方案?如果找到匹配项,您可以设置一个变量,然后在 END 中使用 if 仅当未找到匹配项时才打印消息。

awk -v searchValue="$searchValue" '
   == searchValue { ismatch = 1; print NR".", [=10=]; }
  END { 
    if(!ismatch) print "The value that you entered is not available. Please try again." 
  }' file

此外,我不确定您是否真的想使用 printf...普通的 print 似乎更适合这里。 [=16=] 比列出 , , , .

更容易一些