Linux Bash 连接命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8849681/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 04:03:37  来源:igfitidea点击:

Bash join command

linuxbashunixjoin

提问by AWE

Infile1:

文件 1:

1 a
3 c
4 d
6 f

Infile2:

文件2:

1 a 
2 b
5 e
6 f
7 g
8 h

How do I join these files with the unix join command to get this output:

如何使用 unix join 命令连接这些文件以获取此输出:

1 aa
2 b
3 c
4 d
5 e
6 ff
7 g 
8 h

Dogbanes answer worked but... when I apply dogbanes answer on this file:

Dogbanes 答案有效但是......当我在这个文件上应用 dogbanes 答案时:

27  27
28  22
29  37
30  15
31  21
32  13
33  18
34  24

and this:

和这个:

27  7
28  13
29  6
30  12
31  30
32  5
33  10
34  28

They don't join:

他们不加入:

27  27
27  7
28  13
28  22
29  37
29  6
30  12
30  15
31  21
31  30
32  13
32  5
33  10
33  18
34  24
34  28

The second scenario is tab delimited so I used -t \t

第二种情况是制表符分隔所以我用 -t \t

采纳答案by dogbane

First sortboth files. Then use jointo join on the first field of both files. You also need to pipe the output through sedif you want to remove the space and thus convert a ainto aa. This is shown below:

首先是sort两个文件。然后使用join加入两个文件的第一个字段。您还需要通过管道输出sed,如果你想删除的空间,从而转化a aaa。这如下所示:

$ join -t " " -1 1 -2 1 -a 1 -a 2  <(sort file1) <(sort file2) | sed 's/ \([a-z]\) / /g'
1 aa
2 b
3 c
4 d
5 e
6 ff
7 g
8 h

回答by choroba

Works for me (almost). You should specify -t $'\t'for the tab character, not just -t \t. Bash does not interpret \tunless in $''quotes.

对我有用(几乎)。您应该-t $'\t'为制表符指定,而不仅仅是-t \t. \t除非在$''引号中,否则Bash 不会解释。

join -t $'\t' -o 1.2,2.2 <(echo  $'27\t27
28\t22
29\t37
30\t15
31\t21
32\t13
33\t18
34\t24' | sort) <(echo $'27\t7
28\t13
29\t6
30\t12
31\t30
32\t5
33\t10
34\t28' | sort)
27      7
22      13
37      6
15      12
21      30
13      5
18      10
24      28

回答by Kent

this should work for your both cases:

这应该适用于您的两种情况:

awk 'NR==FNR{a[]=;next;} {a[]=( in a)?a[]:}END{for(x in a)print x,a[x]}' f1 f2|sort

output for case one:

案例一的输出:

1 aa
2 b
3 c
4 d
5 e
6 ff
7 g
8 h

output for case two:

情况二的输出:

27 277
28 2213
29 376
30 1512
31 2130
32 135
33 1810
34 2428