gpt4 book ai didi

linux - 使用awk命令从多个表中过滤数据

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:52:50 26 4
gpt4 key购买 nike

我有 3 个文件,每个文件都有一个表格。文件 1:

RollNo  Name
1 Student1
2 Student2
3 Student3
4 Student4

文件2:

CourseId  CourseName
CS11 Discrete Mathematics
CS12 Business Communication
MT15 Business Management
BM13 Linux

文件 3:

RollNo CourseID  Grade
1 CS11 AB
1 CS12 BC
1 BM13 AB
1 MT15 BB
2 CS11 AA
2 MT15 AB
2 BM13 AB
2 CS12 AA

(注意:文件中没有列名称,即 RollNo、Name、CourseId)

这是我从源代码中找到的 .awk 的脚本文件,它与我想要的非常相似:

BEGIN{
FS=" "
}
{
if(getline tmp < "file3.txt"){
split(tmp, arr)

if(arr[1]==$1){
#print arr[2],arr[3]
cc[i++]=arr[2]

while(getline tmp2 < "file2.txt"){
split(tmp2, arr2)

if(arr2[1]==arr[2]){
#print arr2[2],arr[3]
cName[j++]=arr2[2]
}

}
close("file2.txt")
grade[k++]=arr[3]

}
}
#print tmp
print "RollNo",$1
print "Name",$2
for(i in cc){
print cc[i],grade[i],cName[i]
}

}



我的输出应该是这样的:

Roll No: 1
Name: Student1
CourseID: CS11, CourseName: Discrete Mathematics, Grade:AB
CourseID: CS12, CourseName: Business Communication, Grade:BC
.....
similarly for Roll No: 2.

最佳答案

有一种单线方式适合您:

awk 'ARGIND<3{d[$1]=$2;next}FNR>1{if($1!=x){printf "RollNo:%s\nName:%s\n", $1,d[$1];x=$1} printf "CourseID:%s, CourseName:%s, Grade:%s\n",$2,d[$2],$3}' f1 f2 f3

为了更好的阅读:

awk 'ARGIND<3{d[$1]=$2;next}
FNR>1{
if($1!=x){printf "RollNo:%s\nName:%s\n", $1,d[$1];x=$1}
printf "CourseID:%s, CourseName:%s, Grade:%s\n",$2,d[$2],$3
}' f1 f2 f3

用你的例子测试:

kent$  head f*
==> f1 <==
RollNo Name
1 Student1
2 Student2
3 Student3
4 Student4

==> f2 <==
CourseId CourseName
CS11 Discrete Mathematics
CS12 Business Communication
MT15 Business Management
BM13 Linux

==> f3 <==
RollNo CourseID Grade
1 CS11 AB
1 CS12 BC
1 BM13 AB
1 MT15 BB
2 CS11 AA
2 MT15 AB
2 BM13 AB
2 CS12 AA

kent$ awk 'ARGIND<3{d[$1]=$2;next}FNR>1{if($1!=x){printf "RollNo:%s\nName:%s\n", $1,d[$1];x=$1} printf "CourseID:%s, CourseName:%s, Grade:%s\n",$2,d[$2],$3}' f1 f2 f3
RollNo:1
Name:Student1
CourseID:CS11, CourseName:Discrete, Grade:AB
CourseID:CS12, CourseName:Business, Grade:BC
CourseID:BM13, CourseName:Linux, Grade:AB
CourseID:MT15, CourseName:Business, Grade:BB
RollNo:2
Name:Student2
CourseID:CS11, CourseName:Discrete, Grade:AA
CourseID:MT15, CourseName:Business, Grade:AB
CourseID:BM13, CourseName:Linux, Grade:AB
CourseID:CS12, CourseName:Business, Grade:AA

关于linux - 使用awk命令从多个表中过滤数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18505944/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com