Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
grep使用列表查找文件中的匹配项,并仅打印列表中每个字符串的第一个匹配项_Grep - Fatal编程技术网

grep使用列表查找文件中的匹配项,并仅打印列表中每个字符串的第一个匹配项

grep使用列表查找文件中的匹配项,并仅打印列表中每个字符串的第一个匹配项,grep,Grep,我有一个文件,例如“querys.txt”,它有硬返回分隔字符串。我想使用这个列表在第二个文件“biglist.txt”中查找匹配项 “biglist.txt”中的每个字符串可能有多个匹配项。我只想返回每个查询的第一次命中,并将其写入另一个文件 grep-m1-wf querys.txt biglist.txt>输出 只给我一行输出。我应该有与querys.txt相同行数的输出 有什么建议吗?非常感谢!我搜索了过去的问题,但在阅读几分钟后没有找到完全相同的问题。如果你想在每个文件后“重置计数器”

我有一个文件,例如“querys.txt”,它有硬返回分隔字符串。我想使用这个列表在第二个文件“biglist.txt”中查找匹配项

“biglist.txt”中的每个字符串可能有多个匹配项。我只想返回每个查询的第一次命中,并将其写入另一个文件

grep-m1-wf querys.txt biglist.txt>输出

只给我一行输出。我应该有与querys.txt相同行数的输出

有什么建议吗?非常感谢!我搜索了过去的问题,但在阅读几分钟后没有找到完全相同的问题。

如果你想在每个文件后“重置计数器”,你可以这样做

cat queries.txt | xargs -I{} grep -m 1 -w {} biglist.txt > output
这将使用
xargs
为输入中的每一行调用
grep
一次…应该可以为您解决这个问题

说明:

cat queries.txt   - produce one "search word" per line
xargs -I{}        - take the input one line at a time, and insert it at {}
grep -m 1 -w      - find only one match of a whole word
{}                - this is where xargs inserts the search term (once per call)
biglist.txt       - the file to be searched
> output          - the file where the result is to be written

没有xargs的替代方法(确实应该学习): (此方法假定querys.txt中的行中没有空格)


cat querys.txt |读取目标时;dogrep-m1$target biglist.txt;完成>输出

我可能不完全理解你的问题,但听起来像这样的东西可能有用

cat queries.txt | while read word; do grep "$word" biglist.txt | tee -a output.txt; done

我见过的每个版本的
grep
一次只匹配一种模式。Perl或类似脚本是解决此问题的最佳方法。谢谢Floris。你太棒了。解释也很好,谢谢。这也正是我所需要的。我将研究它们。