grep许多不同的字符串

时间:2012-11-06 22:13:47

标签: grep

我有一个包含100个字符串的文件strings.txt,每个字符串都在一行

string1
string2
...
string100

对于每个字符串,我想找到file_to_look.txt中包含该字符串的所有行。现在,我可以运行grep 100次,如grep string1 file_to_look.txt,然后grep string2 file_to_look.txt等,但这对我来说需要很多打字时间。

有没有办法让我不必这么多打字?

编辑:经过file_to_look.txt只有一次而不是100次的解决方案会很棒,因为我的file_to_look.txt非常大。

5 个答案:

答案 0 :(得分:4)

-f用于传递(GNU)grep模式文件。

grep -f strings.txt file_to_look.txt

答案 1 :(得分:0)

while read line; do grep "$line" file_to_look.txt; done < strings.txt

这正是你所要求的。替代“;”对于您认为合适的新行。

xargs是人们会建议的另一种选择。我的建议是首先寻找另一个替代方案,因为xarg有一堆可能会让事情变得非常错误的问题。

Greg's bash wiki on xargs

答案 2 :(得分:0)

通常xargs用于重复具有多个值的命令:

xargs -I{} grep {} file_to_look.txt < strings.txt

答案 3 :(得分:0)

您可以使用while read执行此操作,如下所示:

cat strings.txt | while read line ; do grep "$line" file_to_look.txt ; done

如需更多替代方法,请查看:

答案 4 :(得分:0)

您可以使用以下简短脚本执行此操作:

#!/bin/bash

file_name=string.txt
file_to_look=file_to_look.txt
patterns=$(tr '\n' '|' $filename)
patterns=${patterns%?} # remove the last |
grep -E $patterns $file_to_look

这会将您的所有搜索模式汇总在一起并使用grep选项一次性移至-E,因此grep只需解析file_to_look.txt一次,而不是100次。