我有两个数据文件,每个文件有3列。如何在这两个文件的第三列中划分相应的元素,并将其写入linux或awk中的另一个文件中。
Experiment Replica Mean
General0 0 408.5
General0 1 461.162
General0 2 428.23
General0 3 373.771
General0 4 396.243
Experiment Replica Mean
General0 0 124.674
General0 1 142.017
General0 2 145.206
General0 3 118.493
General0 4 126.985
Experiment Replica Mean
General0 0 124.674 / 408.5
General0 1
General0 2
General0 3
General0 4
答案 0 :(得分:3)
awk 'FNR==NR{a[$1,$2]=$3;next}FNR==1{print;next}{print $1,$2,$3/a[$1,$2]}' f1 f2
Experiment Replica Mean
General0 0 0.3052
General0 1 0.307955
General0 2 0.339084
General0 3 0.31702
General0 4 0.320473
提示:column -t
是一个很好的工具,可以将输出格式化为表格:
awk .... | column -t
Experiment Replica Mean
General0 0 0.3052
General0 1 0.307955
General0 2 0.339084
General0 3 0.31702
General0 4 0.320473
<强>解释强>
FNR==NR { # FNR==NR is only true in the first file
a[$1,$2]=$3 # Build array, keys are field 1 and 2, value is field 3
next # Skip to the next line in the file
}
FNR==1 { # If we are on the first line in the second file
print # Print the line
next # Go grab the next line
}
{
x=$3/a[$1,$2] # Do the math (the value of a[$1,$2] is $3 from file1)
print $1,$2,x # print the output
}
要以此格式运行脚本,请将其保存到文件script.awk
并执行awk -f script.awk f1 f2
。
答案 1 :(得分:1)
假设相应的记录出现在两个文件的相同位置,文件可以粘贴在一起
paste file1.txt file2.txt |
awk '/Mean/{print($1, $2, $3)} ! /Mean/ {print($1, $2, $6/$3)}'
Experiment Replica Mean
General0 0 0.3052
General0 1 0.307955
General0 2 0.339084
General0 3 0.31702
General0 4 0.320473
这是sudo_O上面的优雅版本:
paste file1.txt file2.txt | awk '{print $1,$2,/Mean/?$3:$6/$3}'