gpt4 book ai didi

linux - 根据列中的公共(public)值合并两个文件

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

我有两个文件,file1file2

文件 1:

00451367210;518       ;
00140913111;21 ;
00551360550;418 ;
00550362618;16 ;
00850362809;13 ;

文件 2

00451367210;041;0
00140913111;021;0
00010010136;021;0
00210010157;041;1
00550362618;121;0
00850362809;021;0
00010010337;021;0
00551360551;021;0
00551360550;121;0

我想根据文件 1 和文件 2 中第 1 列的公共(public)值合并两个文件的列

结果应该是这样的:

00451367210;041;0;518       ;
00140913111;021;0;21 ;
00551360550;121;0;418 ;
00550362618;121;0;16 ;
00850362809;021;0;13 ;

我已经试过了:

join -t";"  -o '0,1.2,1.3,2.2,2.3' File1 File2

但是我有这个:

00451367210;041;0;518       ;
00140913111;021;0;21 ;
join: file 2 is not in sorted order
join: file 1 is not in sorted order
00850362809;021;0;13 ;

知道如何使用 awk 或 join 获得想要的结果吗?

最佳答案

使用 awk 完成工作:

$ awk 'BEGIN{FS=OFS=";"}NR==FNR{a[$1]=$0;next}($1 in a)&&$1=a[$1]' file2 file1
00451367210;041;0;518 ;
00140913111;021;0;21 ;
00551360550;121;0;418 ;
00550362618;121;0;16 ;
00850362809;021;0;13 ;

解释:

  BEGIN { FS=OFS=";" }      # set delimiters 
NR==FNR { a[$1]=$0; next } # hash file 2 on first field to a
($1 in a) && $1=a[$1] # if file1 record is found in a output it

如果您想探索您的加入路径,请尝试使用进程替换对数据进行排序:

$ join -t";"  -o '0,1.2,1.3,2.2,2.3' <(sort file1) <(sort file2)
00140913111;21 ;;021;0
00451367210;518 ;;041;0
00550362618;16 ;;121;0
00551360550;418 ;;121;0
00850362809;13 ;;021;0

关于linux - 根据列中的公共(public)值合并两个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43206737/

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