【问题标题】:AWK - using substr integer as part of if conditionAWK - 使用 substr 整数作为 if 条件的一部分
【发布时间】:2015-02-20 23:31:08
【问题描述】:

我正在尝试使用 awk one liner 来打印文件中子字符串小于定义变量的行。此外,该行必须以字母 E 开头。E 条件有效,但不是我正在寻找的简单 if 'less than' 的结果。我在这里做错了什么?它被合并到一个更大的 bash 脚本中。提前致谢。

#!/bin/bash
minimum_dpt=50

awk -v depth="$minimum_dpt" '{if (/^E/ && int(substr($0,65,6)<depth)) print "Shot: ",substr($0,21,5)," has depth below minimum. Value: ",substr($0,65,6)'}

输入:

E1985020687     1 1  2942984632.99S 88 354.60E 596044.16185585.10000.9 44 826 9
E1985020687     1 1  2943264732.95S 88 359.24E 595917.26185461.80000.5 44 82727
E1985020687     1 1  2944264741.97S 88 450.86E 594520.36185751.92445.3 44 82846
E1985020687     1 1  2945264741.97S 88 450.86E 594520.36185751.90045.3 44 82846

输出:

Shot:   2942  has depth below minimum. Value:  0000.9
Shot:   2943  has depth below minimum. Value:  0000.5
Shot:   2945  has depth below minimum. Value:  0045.3

【问题讨论】:

    标签: bash if-statement awk integer substr


    【解决方案1】:

    你可能打算:

    int(substr($0,65,6))<depth
    

    甚至只是:

    (substr($0,65,6)+0)<depth
    

    而不是你所拥有的:

    int(substr($0,65,6)<depth)
    

    可能有更好的方法来做到这一点,但看不到您的输入和输出 idk...

    【讨论】:

    • 你说得对,艾德。括号的简单错位。它现在按预期工作。感谢您的帮助。
    • 添加了输入/输出字段。
    【解决方案2】:

    类似任务的可能解决方案:

    $ cat input 
    102030405060
    102030405060
    203050601070
    904050308090
    104030607040
    406080903040
    $ awk -v dpt=50 '/^1/ && (int(substr($0, 9, 2)) > int(dpt))' <input
    104030607040
    

    (根据 Ed 的评论编辑,谢谢;)

    【讨论】:

    • UUOC 和无用 print $0。另外 - 你认为substr($0, 9, 2) &gt; dpt 是在进行数字比较还是字符串比较?你确定吗?既然你知道你需要它做什么样的比较,为什么不强迫它去做呢?
    猜你喜欢
    • 2015-07-22
    • 1970-01-01
    • 2020-09-15
    • 2020-11-02
    • 1970-01-01
    • 2015-03-19
    • 1970-01-01
    • 1970-01-01
    • 2011-05-10
    相关资源
    最近更新 更多