我有3个选项卡分隔的文件,如下所示:
档案1:
1 Hhe.7
2 Hpyl.1
10 Hac.2档案2:
3 Hac.2
15 Hpyl.1
33 Hhe.7档案3:
70 Hpyl.1
23 Hhe.7
9 Hac.2如何将这些文件(使用命令行)合并到一个文件中以获得以下输出:
1 33 23 Hhe.7
2 15 70 Hpyl.1
10 3 9 Hac.2发布于 2016-04-12 11:23:08
在一个小型python脚本中,您可以组合无限数量的文件:
#!/usr/bin/env python3
import sys
#read the files, split the lines for reordering
lines = sum([[l.strip().split() for l in open(f).readlines()]\
for f in sys.argv[1:]], [])
# get the unique last sections
values = set(map(lambda x:x[1], lines))
# combine them with the combined first sections
newlist = [[y[0] for y in lines if y[1]==x]+[x] for x in values]
for l in newlist:
print(("\t").join(l))将其复制到一个空文件中,保存为merge.py,通过命令运行它:
python3 /path/to/merge.py file1, file2, file3 (file4, file5 etc.)示例文件的输出:
10 3 9 Hac.2
1 33 23 Hhe.7
2 15 70 Hpyl.1如前所述,如果我添加第四个文件,原则上文件的数量是无限的:
40 Hhe.7
50 Hpyl.1
60 Hac.2然后运行命令:
python3 /path/to/merge.py file1, file2, file3, file4产出如下:
40 23 33 1 Hhe.7
50 70 15 2 Hpyl.1
60 9 3 10 Hac.2发布于 2016-04-12 11:30:43
这是join的一项工作,它可以连接两个文件的公共字段:
$ join -11 -22 -o1.2,1.3,2.1,0 <(join -j2 <(sort -k2,2 f1.txt) <(sort -k2,2 f2.txt)) <(sort -k2,2 f3.txt)
10 3 9 Hac.2
1 33 23 Hhe.7
2 15 70 Hpyl.1由于join一次只接收两个输入文件,所以我们使用进程替换(<())将join-ing的输出与第三个文件一起传递。
https://askubuntu.com/questions/756554
复制相似问题