根据列中的公共值合并两个文件

时间:2017-04-04 12:04:10

标签: linux shell join awk

我有两个文件,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列的常用值组合两个文件的列

结果应如下所示:

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或加入获得想要的结果?

4 个答案:

答案 0 :(得分:1)

使用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路径,请尝试使用流程替换对数据进行排序:

$ 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

答案 1 :(得分:1)

没有awk,如果您想保留join可能会更改的订单,这是一种方法

f() { nl -s';' $1 | sort -t';' -k2;}; 
join -t';' -j2 <(f file1) <(f file2) -o1.2,2.3,1.3,1.1 | 
sort -t';' -k4n | 
sed -r 's/[ 0-9]+$//'


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

答案 2 :(得分:0)

试试这个 -

$ awk -F';' 'NR==FNR{a[$1]=$2;next} $1 in a {print $0 FS a[$1] OFS FS}' f1 f2
00451367210;041;0;518        ;
00140913111;021;0;21         ;
00550362618;121;0;16         ;
00850362809;021;0;13         ;
00551360550;121;0;418        ;

答案 3 :(得分:0)

加入 命令方法:

join -t';' -j1 -o'1.1,2.2,2.3,1.2,1.3'  <(sort /tmp/file1) <(sort /tmp/file2)

输出(已排序):

00140913111;021;0;21        ;
00451367210;041;0;518       ;
00550362618;121;0;16        ;
00551360550;121;0;418       ;
00850362809;021;0;13        ;
相关问题