-1

我有两个文件。(两个真实文件的长度为 50-100 行)。

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

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

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

因此,对于下面示例中的 Smith,分数 3、7、4 的结果应该是:3-5、7-5、4-15(为了便于阅读,我添加了空格、破折号和逗号)

示例文件 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 来说是一项可行的任务,还是我应该去别处看看?

谢谢,

吉姆

4

3 回答 3

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
于 2013-07-11T20:16:43.147 回答
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
于 2013-07-11T20:21:01.420 回答
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]
}
于 2013-07-11T20:17:46.910 回答