select - 使用 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个问题
为什么 if (FNR ~ a[elem]) 有效,但 if (FNR == a[elem]) 无效?
为什么我得到 8 行输出,而不是 2 行?
如果您有更好的解决方案,我很乐意看到它
亲切的问候 :)
解决方案
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
推荐阅读
- javascript - 你能解释一下 lambda 中这个递归调用(带有承诺)背后的逻辑吗?
- python - 有人可以向我解释以下函数的语法吗?Python
- c++ - 为什么我不能在基于范围的 for 循环中使用这种 'void' 类型?
- python - 如何使用 QPlainTextEdit 编辑器结束编辑会话?
- assembly - 用 lea 指令理解基本的汇编代码
- r - 如何命名一列矩阵行名
- python - 我尝试使用 cx_Freeze 创建一个 exe,它只是在启动时关闭,没有错误消息
- javascript - 图片不可见
- mysql - 在 Centos 7.8 上将 innodb_flush_method 设置为 O_DIRECT
- java - LazyInitializationException even though @Transactional is used