2013-12-19 19 views
1

我有一個文件,例如具有硬返回分隔字符串的「queries.txt」。我想用這個列表來查找第二個文件「biglist.txt」中的匹配項。grep使用列表來查找文件中的匹配項,並且僅列出列表中每個字符串的第一個匹配項

「biglist.txt」可能對「queries.txt」中的每個字符串有多個匹配項。我想只返回每個查詢的第一個命中並將其寫入另一個文件。

的grep -m 1 -wf queries.txt biglist.txt>輸出

只給我在輸出一行。我應該輸出與query.txt相同的行數。

對此有何建議?非常感謝!我搜索了過去的問題,但在幾分鐘的閱讀後沒有找到與之類似的案例。

+0

我見過的每個'grep'版本一次只能匹配一個模式。 Perl或類似的腳本是解決這個問題的最好方法。 – Gene

回答

4

如果你想「重置計數器」每個文件後,你可以做

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 
+0

謝謝弗洛里斯。你真了不起。解釋也很好。 – Gina

0

而不xargs的另一種方法(其中之一應確實學會): (此方法假設有在queries.txt線沒有空格)

cat queries.txt | while read target; do grep -m 1 $target biglist.txt; done > outr

+0

謝謝。這也正是我所需要的。我會研究他們兩個。 – Gina

相關問題