搜索(例如AWK中,grep,SED)的字符串,然后寻找上述X布线和下方另一个字符串 [英] search (e.g. awk, grep, sed) for string, then look for X lines above and another string below

查看:142
本文介绍了搜索(例如AWK中,grep,SED)的字符串,然后寻找上述X布线和下方另一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要能够搜索字符串(让使用4320101),打印20行字符串以上并在此之后打印,直到它找到字符串

I need to be able to search for a string (lets use 4320101), print 20 lines above the string and print after this until it finds the string

例如:

Random text I do not want or blank line
16 Apr 2013 00:14:15
id="4320101"
</eventUpdate>
Random text I do not want or blank line

我只是想输出到文件以下结果:

I just want the following result outputted to a file:

16 Apr 2013 00:14:15
id="4320101"
</eventUpdate>

有一个文件,我想这些群体文字的多个例子。

There are multiple examples of these groups of text in a file that I want.

我试图用这个如下:

cat filename | grep "</eventUpdate>" -A 20 4320101 -B 100 > greptest.txt

但它只会显示了20行字符串的任一侧。

But it only ever shows for 20 lines either side of the string.

注:结果
- 行号文是上是不一致的,所以我不能去关闭这些,因此为什么我使用-A 20.结果 - 理想我宁愿它,所以当它的字符串搜索之后,它会停止当它发现然后进行搜索。

Notes:
- the line number the text is on is inconsistent so I cannot go off these, hence why I am using -A 20.
- ideally I'd rather have it so when it searches after the string, it stops when it finds and then carries on searching.

摘要:找到4320101,输出20线之上4320101(或一行空格),低于4320101然后输出的所有行组成

Summary: find 4320101, output 20 lines above 4320101 (or one line of white space), and then output all lines below 4320101 up to

</eventUpdate>

做研究,我不确定如何获得awk中,NAWK或sed的对我有利的工作要做到这一点。

Doing research I am unsure of how to get awk, nawk or sed to work in my favour to do this.

推荐答案

这可能会为你工作(GNU SED):

This might work for you (GNU sed):

sed ':a;s/\n/&/20;tb;$!{N;ba};:b;/4320102/!D;:c;n;/<\/eventUpdate>/!bc' file

编辑:


  • :A; S / \\ n /&安培; / 20;结核病; $ {N;巴}; 这样下去的20行模式空间的窗口! (PS)

  • :B:/ 4320102 D组; 此通过文件移动上面的窗口,直到模式 4320102 是找到。

  • :C; N; /&LT; \\ / eventUpdate&GT; / BC 印在20日线窗口和任何后续行,直到模式! &LT; \\ / eventUpdate方式&gt; 发现

  • :a;s/\n/&/20;tb;$!{N;ba}; this keeps a window of 20 lines in the pattern space (PS)
  • :b;/4320102!D; this moves the above window through the file until the pattern 4320102 is found.
  • :c;n;/<\/eventUpdate>/!bc the 20 line window is printed and any subsequent line until the pattern <\/eventUpdate> is found.

这篇关于搜索(例如AWK中,grep,SED)的字符串,然后寻找上述X布线和下方另一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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