0

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

我在 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 中任何模式的第一次出现的行。

所以期望的输出应该是:

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
4

2 回答 2

2

你可以说:

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

这将打印匹配pattern1,pattern2或的第一行pattern3

正如您所提到的,您可以使用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选项。)grep

于 2013-09-30T14:02:20.133 回答
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
于 2017-01-13T12:43:11.200 回答