首页 > 解决方案 > 使用 AWK 从文件 2 中使用 obs.# 从文件 2 中选择记录

问题描述

我有这些简单的测试文件:这是 fil1,包含我想从 01 02 07 05 10 20 30 25 中选择一些记录

这是keepNR,包含我要从fil1 1 4 7 中提取的记录号

我想要的是来自 fil1 01 (observation/record # 1) 05 (observation/record # 4) 30 (observation/record # 7) 的这些记录

我是 AWK 的新手,但我尝试过这些程序:

使用它,我可以看到观察结果存在 awk 'FNR==NR {a[$1]; 下一个 } { for (elem in a) { print "elem=",elem,"FNR=",FNR,"$1=",$1 }} ' keepNR fil1

我曾希望这会奏效,但我得到的不仅仅是 2 条记录:

awk 'FNR==NR {a[$1]; next } { for (elem in a) { if (FNR ~ a[elem]) print elem,FNR,$1; next }} END{ for (elem in a) { print "END:", elem }}' keepNR fil1 1 1 01 1 2 02 1 3 07 1 4 05 1 5 10 1 6 20 1 7 30 1 8 25

我首先尝试使用 == 而不是 ~,但是没有结果??正如你在这里看到的:

gg@gg:~/bin/awktest$ awk 'FNR==NR {a[$1]; next } { for (elem in a) { if (FNR == a[elem]) print elem,FNR,$1; 下一个 }} ' keepNR fil1 gg@gg:~/bin/awktest$

我也试过 (FNR - a[elem])==0 没有输出

所以我有2个问题

  1. 为什么 if (FNR ~ a[elem]) 有效,但 if (FNR == a[elem]) 无效?

  2. 为什么我得到 8 行输出,而不是 2 行?

如果您有更好的解决方案,我很乐意看到它

亲切的问候 :)

标签: selectawkextract

解决方案


You don't assign to a[$1] so its value is empty: FNR==NR { a[$1]; next }

for (elem in a) sets elem to the keys of a.

if (FNR == a[elem]) compares against the value in a[elem]. The value is empty, so there is no match.

if (FNR ~ a[elem]) tests if FNR matches the empty regex (//), so it always matches.


A simpler method is to test if FNR is a key of a:

awk '
    FNR==NR { a[$1]; next }
    FNR in a { print "FNR="FNR, "$1="$1 }
' keepNR fil1

which should output:

FNR=1 $1=01
FNR=4 $1=05
FNR=7 $1=30

推荐阅读