【问题标题】:Grep a block of text using pattern使用模式 grep 文本块
【发布时间】:2017-06-26 17:43:57
【问题描述】:

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

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

【问题讨论】:

  • 您是否注意到您的问题不清楚?
  • 确定不需要这些行的标准是什么?
  • 您的意思是说您需要具有完整test{1,2,3} 行序列的行并删除所有其他行吗?如果是这样:请在您的问题中添加这样的措辞,以便其他用户清楚。
  • @sorontar 很可能这就是他想要的。保持遵循模式 test1-2-3 的行。

标签: regex bash shell pattern-matching regular-language


【解决方案1】:

一种简单快捷的方法,虽然不是很优雅,但是将其放在一行中,将其拆分为所需的模式,然后再用该模式进行过滤:

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 .

【讨论】:

  • 不错。但在输出中,我有:99 test1 88 test2 10 test3。但我应该有:99 test1 88 test2 10 test3 12 test1 13 test2 14 test3
  • 对我来说按预期工作,也许你有不同的 grep 和 sed 风格。你应该检查没有最后两个命令(grep 和 sed)的输出,看看你得到了什么,然后从那里开始工作。
  • 在你的情况下,我输出了前三行,但我应该得到模式中的所有行 (test1,test2,test3)
猜你喜欢
  • 1970-01-01
  • 2019-07-08
  • 1970-01-01
  • 2012-07-24
  • 2019-01-09
  • 1970-01-01
  • 1970-01-01
  • 2021-12-13
  • 2016-05-05
相关资源
最近更新 更多