如何在多个模式中grep第一个模式实例

时间:2013-09-30 13:52:26

标签: sed awk grep

我有三种不同的模式,我想找出文件中首先出现哪些图案以及哪个parrent出现在文件的最后一行,我需要打印包含第一个和最后一个模式的行。

我在grep下面畏缩,但它仅适用于一种模式。我想一旦它弄清楚如何找到模式的等级,那么最后一个模式的打印可以通过使用“tac”通过相同的逻辑来完成。

grep -m 1 "pattern1" test.txt

我的三个模式是

1.PATTERN1  
2.PATTERN2  
3.PATTERN3  

Line1 this is a sample line for example without  any meaning please ignore
Line2 only meant for giving an example PATTERN2 to make my query clear to all
Line3 this is a sample line for example without  any meaning please ignore
Line4 only meant for giving an example pattern1 to make my query clear to all
Line5 this is a sample line for example without  any meaning please ignore
Line6 only meant for giving an example pattern1 to make my query clear to all
Line7 this is a sample line for example without  any meaning please ignore
Line8 only meant for giving an example pattern2 to make my query clear to all
Line9 this is a sample line for example without  any meaning please ignore
Line10 only meant for giving an example pattern3 to make my query clear to all
Line11 only meant for giving an example pattern1 to make my query clear to all

我想在PATTERN1,PATTERN2,PATTERN3中打印包含任何图案的第一个occarance的行。

所需的输出应为:

First pattern among the three
-------------------------------
Line2 only meant for giving an example PATTERN2 to make my query clear to all

Last instance amoung the three:
-------------------------------
Line11 only meant for giving an example pattern1 to make my query clear to all

2 个答案:

答案 0 :(得分:1)

你可以说:

grep -E -m1 "pattern1|pattern2|pattern3" test.txt

这会打印匹配pattern1pattern2pattern3的第一行。

正如您所提到的,您可以使用tac查找文件中的最后一个匹配模式:

grep -E -m1 "pattern1|pattern2|pattern3" <(tac test.txt)

如果您的grep版本不支持-E,您可以说:

grep -m1 "pattern1\|pattern2\|pattern3" test.txt

编辑:为了找到匹配任何模式的第一行和第一行,您可以说:

grep "pattern1\|pattern2\|pattern3" test.txt | sed -n '1p;$p'

(如果要执行不区分大小写的匹配,请使用-i的{​​{1}}选项。)

答案 1 :(得分:0)

单独使用for循环而不是grep -E构造。使用grep -m1,只返回每个模式的第一个匹配项。添加了-i选项以忽略大小写,否则只显示完全匹配。

for i in PATTERN1 PATTERN2 PATTERN3; do grep -i $i -m1 test.txt; done

这会产生以下结果......

Line4 only meant for giving an example pattern1 to make my query clear to all
Line2 only meant for giving an example PATTERN2 to make my query clear to all
Line10 only meant for giving an example pattern3 to make my query clear to all