搜索文本两种模式,其间多行之间 [英] Search for text between two patterns with multiple lines in between

查看:103
本文介绍了搜索文本两种模式,其间多行之间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的问题。我有一个包含文件:

 更随机文本*富*
那里

随机
文本
这里
*富*富
甚至
更多
随机
文本
这里

更多的随机文本

(之间我想要的结果,这部分从,我加了*澄清的下到foo。*的的不是在文件中。)

我只是想打印出foo的第2实例之间的多条线路。

我试图寻找方法,让富只出现一次,然后将其删除。但是,我没有走到这一步。但是我没有找到删除所有更随机文本使用方法:用sed'/富/,/富/ P',但我无法找到使用sed或awk将只匹配那些并打印输出的方式。

谁能帮我?


解决方案

  $ awk的'/富/ {++℃;下一个}℃== 1'文件
那里

随机
文本
这里$ awk的'/富/ {++℃;下一个}℃== 3'文件
甚至
更多
随机
文本
这里

或GNU AWK的多焦RS你可以这样做:

  $ AWK -v RS =(^ | \\ n)[^ \\ n] * foo的[^ \\ n] *(\\ N | $)''NR == 2 '文件
那里

随机
文本
这里$ AWK -v RS =(^ | \\ n)[^ \\ n] * foo的[^ \\ n] *(\\ N | $)''NR == 4'的文件
甚至
更多
随机
文本
这里

请参阅 http://stackoverflow.com/a/17914105/1745001 印刷的其他方式后一个条件是真实的。

I have a simple question. I have a file containing:

more random text

*foo*
there
is 
random
text
here
*foo*

foo
even
more
random
text
here
foo
more random text

(to clarify between which parts i want the result from, i added the *'s next to foo. The *'s are not in the file.)

I only want to print out the multiple lines between the first 2 instances of foo.

I tried searching for ways to let "foo" occur only once and then remove it. But i didnt get that far. However i did find the way to remove all the "more random text" using: sed '/foo/,/foo/p' but i couldnt find a way using sed, or awk to only match ones and print the output.

Can anyone help me out?

解决方案

$ awk '/foo/{++c;next} c==1' file
there
is
random
text
here

$ awk '/foo/{++c;next} c==3' file
even
more
random
text
here

or with GNU awk for multi-char RS you COULD do:

$ awk -v RS='(^|\n)[^\n]*foo[^\n]*(\n|$)' 'NR==2' file
there
is
random
text
here

$ awk -v RS='(^|\n)[^\n]*foo[^\n]*(\n|$)' 'NR==4' file
even
more
random
text
here

See http://stackoverflow.com/a/17914105/1745001 for other ways of printing after a condition is true.

这篇关于搜索文本两种模式,其间多行之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆