合并具有相同列名的多个txt文件,从文件名创建新列

时间:2016-07-15 10:43:44

标签: shell unix awk

合并具有相同列名的多个txt文件,从文件名创建一个新列。寻找unix解决方案。

例如

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 如何从文件名中向右添加一个附加列?

1 个答案:

答案 0 :(得分: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