Join

加入命令未按預期工作

  • June 24, 2019

我正在嘗試加入兩個具有不同行但有一個共同元素的文件。

文件1:

1/temperature
2/rainfall
3/snowfall
4/windspeed
5/winddirection

文件2:

2008-10-01/1/68
2008-10-02/2/6
2008-10-03/3/4
2008-10-04/4/25
2008-10-05/5/120
2008-10-01/1/89
2008-10-01/4/35
2008-11-01/5/360
2008-10-01/1/45
2008-12-01/1/61
2008-10-10/1/32

我正在嘗試使用以下命令加入這兩個文件

join -t/ -1 1 -2 2 FILE1 FILE2

我期望以下輸出:

1/temperature/2008-10-01/68
1/temperature/2008-10-01/89
1/temperature/2008-10-01/45
1/temperature/2008-12-01/61
1/temperature/2008-10-10/32
2/rainfall/2008-10-02/6
3/snowfall/2008-10-03/4
4/windspeed/2008-10-04/25
4/windspeed/2008-10-01/35
5/winddirection/2008-10-05/120
5/winddirection/2008-11-01/360

但我以這種方式擁有前 5 行:

1/temperature/2008-10-01/68
2/rainfall/2008-10-02/6
3/snowfall/2008-10-03/4
4/windspeed/2008-10-04/25
5/winddirection/2008-10-05/120

請你幫忙我做錯了什麼

join期望對其輸入進行排序(在要連接的欄位上)。在這種情況下(利用 bash shell 的程序替換):

$ join -t/ -1 1 -2 2 FILE1 <(sort -t/ -k2 FILE2)
1/temperature/2008-10-10/32
1/temperature/2008-10-01/45
1/temperature/2008-12-01/61
1/temperature/2008-10-01/68
1/temperature/2008-10-01/89
2/rainfall/2008-10-02/6
3/snowfall/2008-10-03/4
4/windspeed/2008-10-04/25
4/windspeed/2008-10-01/35
5/winddirection/2008-10-05/120
5/winddirection/2008-11-01/360

請注意,所需的排序是詞法而不是數字 - 如果第一列的值FILE1超過 9,那麼您可能還需要對其進行預排序。

引用自:https://unix.stackexchange.com/questions/526542