我正在尝试通过awk读取两个单独的文件,并将第二个文件解析为输出文件。
file1包含数字:
1
2
5
7
10
file2包含一个标题(字段数< 3)和列中的数据值(25列)
_rlnNrOfSignificantSamples #24
_rlnMaxValueProbDistribution #25
300.000000 25425.970703 25000.669922 6.050000 2.000000 56.000000 0.277790 79096.000000 0.100000 000001@Particles/Micrographs/006_particles.mrcs 453.000000 604.000000 1.000000 0.859382 Micrographs/006.mrc 1 -3.469177 -3.469177 0.000000 0.000000 -82.345885 23 9475.876495 1 0.988689
300.000000 25425.970703 25000.669922 6.050000 2.000000 56.000000 0.277790 79096.000000 0.100000 000002@Particles/Micrographs/006_particles.mrcs 431.000000 428.000000 1.000000 0.806442 Micrographs/006.mrc 1 -1.469177 -3.469177 0.000000 0.000000 87.654115 22 9412.959278 1 1.000000
我想从file1读取数字到数组,然后:
经过一天的挣扎,我想出了以下内容:
#!/bin/bash
FieldNum=22
awk -v f=$FieldNum 'FNR==NR{num[$1]; next}
{
# print the header of file2
if(NF < 3) {print > "output"}
# check lines after header
else {if (f in num) {} else {print >> "output"}}
}' $file1 $file2
但结果是从file2打印所有行,因此数组检查不起作用。你能否发现我的错误?
答案 0 :(得分:13)
这个单行应该做你想做的事:
awk 'NR==FNR{a[$0];next}NF<3||!($22 in a)' file1 file2
你的问题是,你有var f
,这是一个数字,我猜它是该列的索引。
但如果您检查了代码,则使用f
作为值,检查数组中是否f
,而不是检查$f
也就是说,如果你给了f=22
,对于file2中的每一行,你检查数组中的常量22。因此输出将是file2中的所有行或者只是file2中的标题,它取决于file1中的常量22。 :)