gpt4 book ai didi

bash - 在 Bash 中生成两个非对称文件之间的差异

转载 作者:行者123 更新时间:2023-12-04 04:43:45 25 4
gpt4 key购买 nike

我有一个包含 2M 个条目的大文本文件 bigFile 和另一个包含 1M 个条目的较小文本文件。

较小文件 File2 中的所有条目都在 File1 中

更大文件中条目的格式是..

helloworld_12345_987654312.zip
helloWorld_12344_987654313.zip
helloWOrld_12346_987654314.zip

较小的文件包含数据,如
987654312
987654313

即文件扩展名 .zip 之前的文件名的最后一部分,有人可以提供任何指示我如何实现这一点

我的尝试是在较小的文件上运行一个循环并对较大的文件执行 grep,如果在较大的文件中找到该文件,则继续删除条目..所以在过程结束时,我会将丢失的条目留在文件中.

尽管此解决方案有效,但效率低下且粗糙。有人可以为这个问题提出更好的方法吗?

最佳答案

Grep 有一个开关 -f它从文件中读取模式。结合 -v它只打印不匹配的线条,你有一个优雅的解决方案。由于您的模式是固定字符串,因此您可以在使用 -F 时显着提高性能。 .

grep -F -v -f smallfile bigfile

我写了一个python脚本来生成一些测试数据:
bigfile = open('bigfile', 'w')
smallfile = open('smallfile', 'w')

count = 2000000
start = 1000000

for i in range(start, start + count):
bigfile.write('foo' + str(i) + 'bar\n')
if i % 2:
smallfile.write(str(i) + '\n')

bigfile.close()
smallfile.close()

以下是我仅使用 2000 行(将计数设置为 2000)运行的一些测试,因为对于更多行,在没有 -F 的情况下运行 grep 所需的时间变得荒谬了。
$ time grep -v -f smallfile bigfile > /dev/null

real 0m3.075s
user 0m2.996s
sys 0m0.028s

$ time grep -F -v -f smallfile bigfile > /dev/null

real 0m0.011s
user 0m0.000s
sys 0m0.012s

Grep 还有一个 --mmap根据手册页可能会提高性能的开关。在我的测试中没有性能提升。

对于这些测试,我使用了 200 万行。
$ time grep -F -v -f smallfile bigfile > /dev/null

real 0m3.900s
user 0m3.736s
sys 0m0.104s

$ time grep -F --mmap -v -f smallfile bigfile > /dev/null

real 0m3.911s
user 0m3.728s
sys 0m0.128s

关于bash - 在 Bash 中生成两个非对称文件之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18508830/

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