Regex 使用模式对文本块进行Grep

Regex 使用模式对文本块进行Grep,regex,bash,shell,pattern-matching,regular-language,Regex,Bash,Shell,Pattern Matching,Regular Language,我有一个简短的文本文件,在这里我应该使用特殊的模式输出数据。我的档案: 99 test1 88 test2 10 test3 11 test1 12 test1 13 test2 14 test3 17 test1 18 test4 一个接一个,从test1到test2再到test3。所以我写了一封信: sed '/test1.*\|test2.*\|test3/!d' filename 在输出中,我得到了以下结果: 99 test1 88 test2 10 test3 11 test1 1

我有一个简短的文本文件,在这里我应该使用特殊的模式输出数据。我的档案:

99 test1
88 test2
10 test3
11 test1
12 test1
13 test2
14 test3
17 test1
18 test4
一个接一个,从test1到test2再到test3。所以我写了一封信:

sed '/test1.*\|test2.*\|test3/!d' filename
在输出中,我得到了以下结果:

99 test1
88 test2
10 test3
11 test1
12 test1
13 test2
14 test3
17 test1
在这种情况下,我有行,我不需要:

11 test1

17 test1
这句话不是一句接一句的。我怎样才能做到我需要的结果?请帮帮我。谢谢你的关注。我应该得到这个结果:

99 test1
88 test2
10 test3
12 test1
13 test2
14 test3

一种简单快捷的方法,虽然不是很优雅,但可以将其放在一行中,按照所需的模式将其打断,然后使用该模式再次过滤:

sed ':a;N;$!ba;s/\n/\\n/g' < filename | \
sed 's/\([0-9][0-9] test1\\n[0-9][0-9] test2\\n[0-9][0-9] test3\\n\)/\n\1\n/g' | \
egrep "[0-9][0-9] test1\\\n[0-9][0-9] test2\\\n[0-9][0-9] test3\\\n" | \
sed 's/\\n/\n/g' | grep .
sed:a;N、 美元!文学士;s/\n/\\n/g'
您是否注意到您的问题不清楚?确定不需要这些行的标准是什么?您的意思是说您需要具有完整序列的
测试{1,2,3}
行并删除所有其他行?如果是这样:请在你的问题中添加这样的措辞,这样其他用户就会明白了。@sorontar最可能就是他想要的。保持符合模式测试1-2-3的线条。不错。但在输出中,我有:99 test1 88 test2 10 test3。但是我应该有:99 test1 88 test2 10 test3 12 test1 13 test2 14 test3对我来说是正常的,也许你对grep和sed有不同的感觉。您应该在没有最后两个命令(grep和sed)的情况下检查输出,以查看您得到了什么,然后从那里开始工作