我曾经注意到使用-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秒.
-
使用 grep 与-f
search.txt 中带有搜索字符串的标志
>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
or
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 不产生输出,这意味着找到的结果是相同的。
也许想尝试一下,否则我建议您查看线程“最快的 grep”,请参阅赛勒斯的评论。