cat file_1
my colour is red
my rose is red
my colour is blue
my rose id blue
cat file_2
red
blue
cat output_file should be
my colour is red
my colour is blue
在这里我正在使用
cat file_2 | while read line;do cat file_1 | grep "$line" | head -1;done
在这里我试图得到包含pattern "red" and "blue"
其中存在的最上面的行file_2
还有其他方法可以做as fast as possible
,,而循环又要花时间
您可以使用一种while
构造来遍历的模式file2
,然后使用-m 1
withgrep
来在第一次匹配后停止file1
:
while IFS= read -r i; do grep -Fm1 "$i" file1; done <file2
-F
从字面上看待模式-m 1
使得grep
退出第一场比赛后,Shell循环通常效率不高,但由于模式列表较小,因此在这种情况下可以使用。
更快的替代方案,xargs
:
xargs -a file2 -n1 -P2 -I'{}' grep -Fm1 {} file1
使用更多并行进程(-P
)获得更多模式。
例子:
% while IFS= read -r i; do grep -Fm1 "$i" file1; done <file2
my colour is red
my colour is blue
% xargs -a file2 -n1 -P2 -I'{}' grep -Fm1 {} file1
my colour is blue
my colour is red
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句