【问题标题】:Using Awk to print the unavailable record only once使用 awk 只打印一次不可用的记录
【发布时间】:2022-01-15 15:30:31
【问题描述】:

我正在编写一个内部看起来像这样的 awk 脚本:

awk -v searchValue="$searchValue" '{ if ($3 == searchValue){
                                                    printf NR".", $1, $2, $3, $4                                          
                                     }
                                     else if ($3!=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.

【问题讨论】:

  • 如果您不缩进 30 个字符(或缩进很多),您的代码会更容易阅读,因此需要滚动条才能看到它。此外,切勿将printf foo 用于任何可以包含输入数据的foo,例如$1,因为当输入包含 printf 格式字符时,它会神秘地失败,请始终使用 printf "%s", foo 代替。

标签: linux if-statement awk


【解决方案1】:

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

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

另外我不确定你是否真的想使用printf...普通的旧print 似乎更适合这里。而且$0 比列出$1, $2, $3, $4 要容易一些。

【讨论】:

  • 谢谢大卫。你真的帮了我很多
猜你喜欢
  • 1970-01-01
  • 2010-12-18
  • 2020-04-16
  • 2018-12-31
  • 1970-01-01
  • 2018-07-02
  • 2021-03-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多