2017-07-03 112 views
0

你能幫我合併兩個文件嗎? 實際上它的行應該被合併,並且每一行都有相同的ID(例如在這個例子中是1或2)。如何合併2個差異文件中的行(linux awk)

文件1

1#first#scott#prince01 
2#second#scott#prince02 

文件2

1#scott#prince01#88129 
2#scott#prince02#34 

最後

1#first#scott#prince01#1#scott#prince01#88129 
2#second#scott#prince02#2#scott#prince02#34 

回答

4

在您簡單的情況下,這將是足夠使用join命令:

join -t'#' File1 File2 

輸出:

1#first#scott#prince01#scott#prince01#88129 
2#second#scott#prince02#scott#prince02#34 

  • -t'#' - 指定字段分隔
+0

OMG。很簡單。我們可以在所有其他unix中使用'join'命令嗎? – Sigularity

+0

@Sigularity,'join'是來自GNU coreutils的標準工具https://www.gnu.org/software/coreutils/manual/ – RomanPerekhrest

0

在AWK:

$ awk 'BEGIN{FS=OFS="#"}NR==FNR{a[$1]=$0;next}($1 in a){print a[$1],$0}' file1 file2 
1#first#scott#prince01#1#scott#prince01#88129 
2#second#scott#prince02#2#scott#prince02#34 

解釋:

$ awk '   
BEGIN{ 
    FS=OFS="#"  # set FS AND OFS to # 
} 
NR==FNR {   # for the first file 
    a[$1]=$0  # hash records, use $1 as key 
    next   # skip to next record 
} 
($1 in a) {   # for the second file, if key found in the hash 
    print a[$1],$0 # output 
}' file1 file2 
+1

每行應與'#'合併。謝謝。 – Sigularity

+0

@Sigularity對不起,我的壞。固定。 –

0

一些更多的方式(我假定文件進行排序)

輸入

$ cat f1 
1#first#scott#prince01 
2#second#scott#prince02 

$ cat f2 
1#scott#prince01#88129 
2#scott#prince02#34 

使用

$ pr -mtJS'#' f1 f2 
1#first#scott#prince01#1#scott#prince01#88129 
2#second#scott#prince02#2#scott#prince02#34 

使用

$ paste -d'#' f1 f2 
1#first#scott#prince01#1#scott#prince01#88129 
2#second#scott#prince02#2#scott#prince02#34 
+0

謝謝。它運作良好。 – Sigularity

0
$ awk '{a[FNR]= a[FNR]=="" ? $0 :a[FNR]"#"$0}END{for(i in a)print a[i]}' File1 File2 
1#first#scott#prince01#1#scott#prince01#88129 
2#second#scott#prince02#2#scott#prince02#34 

簡要說明,

  • 存儲在[FNR]
  • a[FNR]= a[FNR]=="" ? $0 :a[FNR]"#"$0爲線#FNR特定值:其保存爲$0如果沒有初始值是在一個[FNR ],否則存儲a[FNR]"#"$0
+0

謝謝。有用! – Sigularity

+0

它不尊重ID字段,但FNR。如果您在'file1'中更改記錄1和2的順序,它會產生錯誤的輸出,如#2#second#scott#prince02#1#scott#prince01#88129'。至少在ID字段中添加要訂購的數據的要求。 –

+0

你沒錯,這個方法只能在ID和FNR完全相同的情況下工作。 – CWLiu