2013-07-11 33 views
-1

我有两个文件。 (这两个真实文件长度将是50-100行)。使用AWK从1个文件中使用3个值从第二个文件中查找3个值

文件1具有由4个字段组成的记录。 名称;原始阅读分数;原始数学分数;原始科学得分

文件2具有由4个字段组成的记录(查找表) 原始得分;转换阅读;转换数学;已转换科学 此文件可能包含重复条目,用于原始分数 的任何给定转换,例如,原始分数8和9两者的科学换算分数相等。

我想创建一个由7个字段组成的输出文件: 名称;原始阅读分数;转换阅读;原始数学分数;转换数学;原始科学评分;转换科学

所以对于史密斯在我下面的例子中,得分 3,7,4的结果应该是: 3-5,7-5,4-15(我已经添加了空格,破折号和逗号对于readabilty)

示例文件1(名称和3个原始分数)

Smith;3;7;4 
Jones;8;2;9 
Doe;1;9;4 

示例文件2(原始和3转换的分数)

1;1;1;1 
2;3;2;5 
3;5;2;10 
4;6;3;15 
5;8;4;22 
6;11;5;35 
7;15;5;43 
8;18;6;50 
9;20;7;50 

所需的输出连接勒(名称,然后交替3原料和3转换的分数)

Smith;3;5;7;5;4;15 
Jones;8;18;2;2;9;50 
Doe;1;1;9;7;4;15 

因此,我认为我想读取文件2分成数组,然后在文件1中读出,使用阵列来查找转换后的分数,然后输出名称和3组原始和转换分数。

这是AWK的可执行任务,还是我应该在其他地方看看?

感谢,

吉姆

回答

2

这应该工作:

awk -F';' -v OFS=";" 'NR==FNR{a[$1]=$0;next} 
{ 
split(a[$2],b) 
split(a[$3],c) 
split(a[$4],d) 
print $1,$2,b[2],$3,c[3],$4,d[4]}' file2 file1 
+0

我不明白第一行的-v。我调整了一下,它工作正常。我将不得不阅读拆分命令。谢谢。 – user2574126

+0

@ user2574126和别人一样'BEGIN {FS = OFS =“;”}' – Kent

1

我相信这应该这样做:

awk 'BEGIN{OFS=FS=";"}NR==FNR{s[$1,1]=$2;s[$1,2]=$3;s[$1,3]=$4;next}{print $1,$2,s[$2,1],$3,s[$3,2],$4,s[$4,3]}' table people 

注意文件的逆转。

的解释:

# Before processing any lines 
BEGIN{ 
    # Set the input and output field separators 
    OFS=FS=";" 
} 
# For the first file 
NR==FNR { 
    # Record the mappings - $1 is the first field, $2 the second, etc. 
    s[$1,1]=$2; 
    s[$1,2]=$3; 
    s[$1,3]=$4; 
    # Skip to the next line. This is often used 
    # instead of putting the opposite condition 
    # on the rest of the blocks, or putting a big 
    # if/else in one block. 
    next 
} 
# Every line that reaches here, i.e. the second file 
{ 
    # Print the student's name followed by each score raw and mapped. 
    print $1, $2, s[$2,1], $3, s[$3,2], $4, s[$4,3] 
} 
+0

好评!祝你们好运。 – shellter

+0

这很好!并感谢您的解释。我应该能够修改它类似的问题。吉姆 – user2574126

1

这应该工作:

awk ' 
BEGIN{FS=OFS=";"} 
NR==FNR{cr[$1]=$2;cm[$1]=$3;cs[$1]=$4;next} 
{print $1,$2,cr[$2],$3,cm[$3],$4,cs[$4]} 
' file2 file1 

输出

Smith;3;5;7;5;4;15 
Jones;8;18;2;2;9;50 
Doe;1;1;9;7;4;15 
+0

工程就像一个魅力。 – user2574126

相关问题