gpt4 book ai didi

awk - 如何通过 awk 中的临时公共(public)列连接两个 CSV 文件?

转载 作者:行者123 更新时间:2023-12-05 09:09:43 24 4
gpt4 key购买 nike

我有两个 CSV 文件,格式为

文件1

A,44
A,21
B,65
C,79

文件2

A,7
B,4
C,11

我用 awk 作为

awk -F, 'NR==FNR{a[$1]=$0;next} ($1 in a){print a[$1]","$2 }' file1.csv file2.csv

生产

A,44,7
A,21,7
B,65,4
C,79,11

a[$1]file1 打印整行。如何省略两个文件中的第一列(第一列仅用于匹配第二列)以生成:

44,7
21,7
65,4
79,11

换句话说,如何将列从第一个文件传递到打印 block ,就像 $2 对第二个文件所做的那样?

最佳答案

能否请您尝试仅在显示的示例上进行跟踪、测试和编写。

awk 'BEGIN{FS=OFS=","} FNR==NR{a[$1]=$2;next} ($1 in a){print $2,a[$1]}' file2 file1

说明:为以上添加详细说明。

awk '                     ##Starting awk program from here.
BEGIN{ ##Starting BEGIN section from here.
FS=OFS="," ##Setting field and output field separator as comma here.
}
FNR==NR{ ##Checking condition FNR==NR which will be TRUE when file2 is being read.
a[$1]=$2 ##Creating array a with index $1 and value is $2 from current line.
next ##next will skip all further statement from here.
}
($1 in a){ ##Statements from here will be executed when file1 is being read and it's checking if $1 is present in array a then do following.
print $2,a[$1] ##Printing 2nd field and value of array a with index $1 here.
}
' file2 file1 ##Mentioning Input_file names here.

所示示例的输出如下。

44,7
21,7
65,4
79,11


第二个解决方案: 更通用的解决方案,考虑到您的两个 Input_files 可能有重复项,在这种情况下,它会将 Input_file1 中 A 的第一个值打印到 Input_file2 的第一个值等等。

awk '
BEGIN{
FS=OFS=","
}
FNR==NR{
a[$1]
b[$1,++c[$1]]=$2
next
}
($1 in a){
print $2,b[$1,++d[$1]]
}
' file2 file1

关于awk - 如何通过 awk 中的临时公共(public)列连接两个 CSV 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62153264/

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