【问题标题】:Merge multiple txt files with same column names creating a new column from the filenames合并具有相同列名的多个 txt 文件,从文件名创建一个新列
【发布时间】:2016-07-15 10:43:43
【问题描述】:

合并具有相同列名的多个 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

预期输出 合并文件.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 如何从文件名的右侧添加一个附加列?

【问题讨论】:

    标签: shell unix awk


    【解决方案1】:

    你可以使用这个 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
    

    【讨论】:

    • 谢谢。如果有超过 100 个不同名称的文件,我该怎么办。我如何替换文件[123] |列-t
    • 好的,我现在搞定。 awk 'FNR==1{if (NR==1) print "filename", $0;下一个} {打印文件名,$0}' *txt > merge_files.txt
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 2017-06-18
    • 1970-01-01
    • 1970-01-01
    • 2019-07-13
    • 2021-09-24
    • 1970-01-01
    相关资源
    最近更新 更多