【问题标题】:awk - Print all lines containing the Max value found in the initial analysis (Containing U+2500 Unicode Character between the lines)awk - 打印包含在初始分析中找到的最大值的所有行(行间包含 U+2500 Unicode 字符)
【发布时间】:2021-07-01 18:45:05
【问题描述】:

我有一个问题已在此处awk - Print all lines containing the Max value found in the initial analysis 得到解答,但现在需要对其进行调整,以便在两行之间存在 U+2500 unicode 字符时进行调整。

问题如下,我有一个新的入口文件如下:

0.0008    6
────────────
9.0    10
────────────
9.0    19
────────────
0.7    33

如果我尝试使用awk - Print all lines containing the Max value found in the initial analysis 的答案找到最大值,则输出始终如下所示:

──────
──────
──────

这不是预期的出口,但我应该得到类似的东西:

9.0    10
9.0    19

注意: 创建此问题是为了不影响 awk - Print all lines containing the Max value found in the initial analysis 中标记为“已解决”的解决方案的选择。

【问题讨论】:

    标签: indexing awk line


    【解决方案1】:

    你也可以使用这个 2 pass awk:

    awk '$1+0 != $1 {next} FNR==NR {if (max < $1) max=$1; next} $1 == max' file{,}
    
    9.0    10
    9.0    19
    

    我们在第一阶段计算最大值并忽略所有$1 为非数字的行,然后在第二阶段打印所有$1max 值相同的记录。

    【讨论】:

      【解决方案2】:

      使用您展示的示例,请尝试以下操作。用 GNU awk 编写和测试。

      awk '
      $1+0==$1{
        max=(max>$1?max:$1)
        arr[$1]=(arr[$1]?arr[$1] ORS:"")$0
      }
      END{
        print arr[max]
      }
      '  Input_file
      

      说明:为上述解决方案添加详细说明。

      awk '                                     ##Starting awk program from here.
      $1+0==$1{                                 ##Checking condition if 1st field is an integer.
        max=(max>$1?max:$1)                     ##Create max variable by having maximum value out of 1st field and max variable here.
        arr[$1]=(arr[$1]?arr[$1] ORS:"")$0      ##Create array with index of $1 and keep adding its value to it wit same index values.
      }
      END{                                      ##Starting END block of this program from here.
        print arr[max]                          ##Printing array arr value with key of max here.
      }
      '  Input_file                             ##Mentioning Input_file name here.
      

      注意:根据@karafka 的建议添加$1+0==$1 以便科学记数法不会遗漏负数

      【讨论】:

      • regex 仍然会遗漏科学记数法、负数、以小数点开头且没有前导零的数字等。
      • @karakfa,谢谢你告诉我,如果我现在改变我的答案,它就会变成你的谎言 :)
      • 嗯,一开始就是你的。一旦你改变它,我会删除我的。
      • @karakfa,谢谢您的好意 :) 先生,您太好了,如果您想保留它,请保留它,我将删除我的没问题,因为您的已经足够好了,为什么要删除:)
      猜你喜欢
      • 2021-06-28
      • 1970-01-01
      • 1970-01-01
      • 2019-07-01
      • 1970-01-01
      • 2021-06-18
      • 2017-12-04
      • 2013-05-09
      • 2021-05-08
      相关资源
      最近更新 更多