我曾经注意到使用-E 或多个-e 参数比使用-f 更快。请注意,这可能不适用于您的问题,因为您要在较大的文件中搜索 50,000 个字符串。但是,我想向您展示可以做什么以及可能值得测试的内容:
这是我注意到的细节:
有 1.2GB 的文件填充随机字符串。
>ls -has | grep string
1,2G strings.txt
>head strings.txt
Mfzd0sf7RA664UVrBHK44cSQpLRKT6J0
Uk218A8GKRdAVOZLIykVc0b2RH1ayfAy
BmuCCPJaQGhFTIutGpVG86tlanW8c9Pa
etrulbGONKT3pact1SHg2ipcCr7TZ9jc
.....
现在我想使用不同的 grep 方法搜索字符串“ab”、“cd”和“ef”:
- 使用不带标志的 grep,一次搜索一个:
grep "ab" strings.txt > m1.out
2,76s user 0,42s system 96% cpu 3,313 total
grep "cd" strings.txt >> m1.out
2,82s user 0,36s system 95% cpu 3,322 total
grep "ef" strings.txt >> m1.out
2,78s user 0,36s system 94% cpu 3,360 total
因此,搜索总共需要将近 10 秒。
-
在 search.txt 中使用带有 -f 标志的 grep 和搜索字符串
>cat search.txt
ab
cd
ef
>grep -F -f search.txt strings.txt > m2.out
31,55s user 0,60s system 99% cpu 32,343 total
由于某些原因,这需要将近 32 秒。
-
现在使用-e 的多种搜索模式
grep -E "ab|cd|ef" strings.txt > m3.out
3,80s user 0,36s system 98% cpu 4,220 total
或
grep --color=auto -e "ab" -e "cd" -e "ef" strings.txt > /dev/null
3,86s user 0,38s system 98% cpu 4,323 total
使用-E 的第三种方法只用了4.22 秒 来搜索文件。
现在让我们检查结果是否相同:
cat m1.out | sort | uniq > m1.sort
cat m3.out | sort | uniq > m3.sort
diff m1.sort m3.sort
#
diff 不产生输出,这意味着找到的结果是相同的。
也许想试一试,否则我建议您查看线程“Fastest possible grep”,请参阅 Cyrus 的评论。