我有一个包含 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/