2016-07-15 88 views
1

合併具有相同列名的多個txt文件,從文件名中創建一個新列。尋找一個unix解決方案。合併具有相同列名的多個txt文件,從文件名中創建一個新列

例如。

FILE1.TXT

country player age 
USA  Ben  24 

FILE2.TXT

country player age 
UK  John  27 

file3.txt

country player age 
Spain  Alex  28 
Germany Hubber 26 

預期輸出 merged_files.txt

filename country player age 
file1  USA  Ben  24 
file2  UK  John  27 
file3  Spain  Alex  28 
file3  Germany Hubber 26 

我試過$ cat file*.txt > merged_files.txt 如何從文件名右邊添加一列?

回答

2

您可以使用此awk命令:

awk 'FNR==1{if (NR==1) print "filename", $0; next} {print FILENAME, $0}' file[123] 

filename country player age 
file1 USA  Ben  24 
file2 UK  John  27 
file3 Spain  Alex  28 
file3 Germany Hubber 26 

要獲取表格報告:

awk 'FNR==1{if (NR==1) print "filename", $0; next} {print FILENAME, $0}' file[123] | 
column -t 

filename country player age 
file1  USA  Ben  24 
file2  UK  John 27 
file3  Spain Alex 28 
file3  Germany Hubber 26 
+0

感謝。如果有超過100個名稱不同的文件,我該怎麼辦?我如何替換文件[123] |列-t – panbar

+1

好吧,我現在就玩。 awk'FNR == 1 {if(NR == 1)print「filename」,$ 0; next} {print FILENAME,$ 0}'* txt> merged_files.txt – panbar

相關問題