0

我有两个数据文件,每个文件都有 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 
4

2 回答 2

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.

于 2013-04-25T16:07:34.327 回答
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}'
于 2013-04-25T16:14:55.437 回答