给定两个文件file1.txt
abc def \t 123 456
jkl mno \t 987 654
foo bar \t 789 123
bar bar \t 432
and file2.txt
foo bar \t hello world
abc def \t good morning
xyz \t 456
任务是提取第一列匹配的行并实现:
abc def \t 123 456 \t good morning
foo bar \t 789 123 \t hello world
我可以用Python这样做:
from io import StringIO
file1 = """abc def \t 123 456
jkl mno \t 987 654
foo bar \t 789 123
bar bar \t 432"""
file2 = """foo bar \t hello world
abc def \t good morning
xyz \t 456"""
map1, map2 = {}, {}
with StringIO(file1) as fin1:
for line in file1.split('\n'):
one, two = line.strip().split('\t')
map1[one] = two
with StringIO(file2) as fin2:
for line in file2.split('\n'):
one, two = line.strip().split('\t')
map2[one] = two
for k in set(map1).intersection(set(map2)):
print('\t'.join([k, map1[k], map2[k]]))
实际的任务文件有数十亿行,是否有更快的解决方案,无需加载所有内容并保留哈希图/字典?
也许使用 unix/bash 命令?对文件进行预排序会有帮助吗?
The join
命令有时很难使用,但这里很简单:
join -t $'\t' <(sort file1.txt) <(sort file2.txt)
使用 bash 的ANSI-C 引用 https://www.gnu.org/software/bash/manual/bash.html#ANSI_002dC-Quoting指定制表符分隔符,以及流程替代 https://www.gnu.org/software/bash/manual/bash.html#Process-Substitution将程序输出视为文件。
要查看输出,请将以上内容通过管道传输到cat -A
查看表示为的选项卡^I
:
abc def^I123 456^Igood morning$
foo bar^I789 123^Ihello world$
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)