gpt4 book ai didi

linux - 在 Linux 中 : merge two very big files

转载 作者:太空宇宙 更新时间:2023-11-04 09:41:16 25 4
gpt4 key购买 nike

我想合并两个文件(一个是空格分隔的,另一个是制表符分隔的)只保留两个文件之间匹配的记录:

文件 1:空格分隔

A B C D E F G H
s e id_234 4 t 5 7 9
r d id_45 6 h 3 9 10
f w id_56 2 y 7 3 0
s f id_67 2 y 10 3 0

文件 2:制表符分隔

I L M N O P
s e 4 u id_67 88
d a 5 d id_33 67
g r 1 o id_45 89

我想匹配文件 1 的字段 3(“C”)和文件 2 的字段 5(“O”),并像这样合并文件:

文件 3:制表符分隔

I L M N O P A B D E F G H
s e 4 u id_67 88 s f 2 y 10 3 0
g r 1 o id_45 89 r d 6 h 3 9 10

文件 1 中的某些条目未出现在文件 2 中,反之亦然,但我只想保留交集(公共(public) ID)。

我真的不关心顺序。

我不想使用 join,因为这些文件确实很大且未排序,并且 join 之前需要按公共(public)字段排序,这需要很长时间和大量内存。

我尝试过使用 awk 但没有成功

awk > file3 'NR == FNR {
f2[$3] = $2; next
}
$5 in f2 {
print $0, f2[$2]
}' file2 file1

有人可以帮帮我吗?

非常感谢

最佳答案

嗯.. 理想情况下,您会寻求避免 n^2 解决方案,而这正是基于 awk 的方法似乎需要的。对于 file1 中的每条记录,您必须扫描 file2 以查看是否发生。这就是时间的流逝。

我建议为此编写一个 python(或类似)脚本,并为其中一个文件构建 map id-> 文件位置,然后在扫描另一个文件时查询它。这会给你一个 nlogn 运行时,至少对我来说,这看起来是你在这里可以做的最好的事情(使用哈希作为索引会给你带来寻找文件 pos 的昂贵问题)。

事实上,这是执行此操作的 Python 脚本:

f1 = file("file1.txt")

f1_index = {}

# Generate index for file1
fpos = f1.tell()
line = f1.readline()
while line:
id = line.split()[2]
f1_index[id] = fpos
fpos = f1.tell()
line = f1.readline()

# Now scan file2 and output matches
f2 = file("file2.txt")
line = f2.readline()
while line:
id = line.split()[4]
if id in f1_index:
# Found a matching line, seek to file1 pos and read
# the line back in
f1.seek(f1_index[id], 0)
line2 = f1.readline().split()
del line2[2] # <- Remove the redundant id_XX
new_line = "\t".join(line.strip().split() + line2)
print new_line
line = f2.readline()

关于linux - 在 Linux 中 : merge two very big files,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21144266/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com