AWK 字段包含数字范围



我正在尝试使用awk从分号(;(分隔的文本文件中输出行,其中第三个字段包含特定范围内的数字。

例如
[root@example ~]# cat foo.csv
john doe; lawyer; section 4 stand 356; area 5
chris thomas; carpenter;  stand 289 section 2; area 5
tom sawyer; politician; stan 210 section 4; area 6

我希望awk给我所有行,其中第三个字段包含 200 到 300 之间的数字,而不考虑字段中的其他文本。

您可以使用正则表达式,如下所示:

awk -F; '$3 ~ /y2[0-9][0-9]y/' a.csv

允许您在命令行中简单地传递边界而不更改正则表达式的更好版本可能如下所示:

(由于它是一个更复杂的脚本,我建议将其保存到文件中(

filter.awk

BEGIN { FS=";" }
{
    # Split the 3rd field by sequences of non-numeric characters
    # and store the pieces in 'a'. 'a' will contain the numbers
    # of the 3rd field (plus an optional empty strings if $3 does
    # not start or end with a number)
    split($3, a, "[^0-9]+")
    # iterate through a and check if a number is within the range
    for(i in a){
        if(a!="" && a[i]>=low && a[i]<high){
            print
            next
        }
    }
}

这样称呼它:

awk -v high=300 -v low=200 -f filter.awk a.csv

grep 替代品:

grep '^[^;]*;[^;]*;[^;]*b2[0-9][0-9]b' foo.csv

输出:

chris thomas; carpenter;  stand 289 section 2; area 5
tom sawyer; politician; stan 210 section 4; area 6

如果300应该是包含边界,则可以使用以下方法:

grep '^[^;]*;[^;]*;[^;]*b(2[0-9][0-9]|300)b' foo.csv

最新更新