因为我在学习awk;我发现FNR==NR方法是处理两个文件的一种非常常见的方法。如果FNR==NR;然后是first file,当从连接文件中读取每一行时FNR重置为,这意味着它显然是.1!(FNR==NR)second file
当涉及三个或更多文件时,我看不到第二个和第三个文件的方式,因为它们的!(FNR==NR)条件相同。这让我试图弄清楚怎么会有类似FNR2and的东西FNR3?
所以我实现了一个方法来处理三个文件awk。假设FNR1 FNR2 FNR3每个文件都有。对于我制作for loop的每个单独运行的文件。每个循环的条件都是相同的NR==FNR#,实际上得到了我的预期:
所以我想知道是否有更清醒、更简洁的方法awk可以用下面的代码提供类似的结果
示例文件内容
$ cat file1
X|A1|Z
X|A2|Z
X|A3|Z
X|A4|Z
$ cat file2
X|Y|A3
X|Y|A4
X|Y|A5
$ cat file3
A1|Y|Z
A4|Y|Z
AWK for 循环
$ cat fnrarray.sh
awk -v FS='[|]' '{ for(i=FNR ; i<=NR && i<=FNR && NR==FNR; i++) {x++; print "NR:",NR,"FNR1:",i,"FNR:",FNR,"\tfirst file\t"}
for(i=FNR ; i+x<=NR && i<=FNR && NR==FNR+x; i++) {y++; print "NR:",NR,"FNR2:",i+x,"FNR:",FNR,"\tsecond file\t"}
for(i=FNR ; i+x+y<=NR && i<=FNR && NR==FNR+x+y; i++) {print "NR:",NR,"FNR3:",i+x+y,"FNR:",FNR,"\tthird file\t"}
}' file1 file2 file3
当前和所需的输出
$ sh fnrarray.sh
NR: 1 FNR1: 1 FNR: 1 first file
NR: 2 FNR1: 2 FNR: 2 first file
NR: 3 FNR1: 3 FNR: 3 first file
NR: 4 FNR1: 4 FNR: 4 first file
NR: 5 FNR2: 5 FNR: 1 second file
NR: 6 FNR2: 6 FNR: 2 second file
NR: 7 FNR2: 7 FNR: 3 second file
NR: 8 FNR3: 8 FNR: 1 third file
NR: 9 FNR3: 9 FNR: 2 third file
你可以看到NR对齐FNR#并且它是可读的 which NRis for which file#。
另一种方法
我在FNR==1{++f} f==1 {}这里找到了这个方法使用 awk 处理 3 个文件
arr1[1]但是每次读取新行时,此方法正在替换
失败尝试 1
$ awk -v FS='[|]' 'FNR==1{++f} f==1 {split($2,arr); print arr1[1]}' file1 file2 file3
A1
A2
A3
A4
for 循环成功(arr1[1]未更改)
$ awk -v FS='[|]' '{for(i=FNR ; i<=NR && i<=FNR && NR==FNR; i++) {arr1[++k]=$2; print arr1[1]}}' file1 file2 file3
A1
A1
A1
A1