【问题标题】:How to join two CSV files by a temporary common column in awk?如何通过 awk 中的临时公共列连接两个 CSV 文件?
【发布时间】:2020-06-03 00:31:18
【问题描述】:

我有两个 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

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

【问题讨论】:

  • 如果您的文件包含重复的键,您的方法将不起作用,例如文件 1 中的 A

标签: awk


【解决方案1】:

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

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

【讨论】:

  • 完美运行。 $2a[$1]=$2 中的作用是什么?我只是想学习。
  • @Googlebot,当然,会在一两分钟内添加详细说明。
  • 聪明的解决方案(第二个),你可以省略a数组。检查多维数组,可以(idx1,idx2,idxN) in mdArray
  • 没问题,您提供的许多 awk 解决方案都很棒!如果我没记错的话,m-d 数组是 awk 标准的东西。但是,我不知道它是否从一开始就被引入。顺便说一句,gawk 的a[i][j] 也很方便。但忘记了它的名字:多阵列?嵌套数组?或者什么
  • +1 为带有解释的漂亮代码,Ravinder。我做了一些更正,如果我做错了请告诉我。
【解决方案2】:

您可以使用 join 命令加入它们,并选择要在输出中包含哪些字段:

kent$  join -t',' -o 1.2,2.2 file1 file2
44,7                                         
21,7
65,4
79,11

【讨论】:

  • join加入前不需要排序吗?这没什么大不了的,只是为了确保。
  • @Googlebot 不,加入命令不需要排序。当然,如果您期望排序后的连接输出,您可能需要排序。
  • 太好了,您的解决方案就像一个魅力,但我不得不接受另一个答案,因为这个问题专门针对 awk。谢谢,您的简单解决方案将有很大帮助。
  • @Googlebot 没问题。在这种特殊情况下,join 更容易,因为它处理 dup。情况下,R.S. 的 awk 答案很聪明。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-16
  • 1970-01-01
  • 2023-04-10
  • 2020-08-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多