如果另一个grep匹配,则使用Unix Bash shell命令来grep一些文本 [英] Unix Bash shell command to grep some text if another grep matches

查看:127
本文介绍了如果另一个grep匹配,则使用Unix Bash shell命令来grep一些文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在unix目录中有一个XML文件。我想搜索一些字符,如果存在,然后grep位于该匹配行之前3行的文本。

I have an XML file in unix directory. I would like to search for some character if that is present, then grep the text located 3 lines before this matched line,.

这是我的文件:( abc.xml)

<task Col="5" Object="BCD">
<checkpoint TcpOn="0"/>
<after ActFlg="0"/>
</task>
<task Col="6" Object="ABCD">
<checkpoint TcpOn="0"/>
<after ActFlg="1"/>
</task>
<task Col="7" Object="ABCDE">
<checkpoint TcpOn="0"/>
<after ActFlg="1"/>
</task>

Unix代码:

Unix Code:

grep -i 'actflg="1"' abc.xml

当前答案:这是返回它所在的行。

Current Answer: This is returning the line where it is located.

<after ActFlg="1"/>
<after ActFlg="1"/>

我想要的是:(我想再做一次grep如果发现actflg =1,则显示输出如下 ...)

What i Want is : (i want to do a further grep to display output as follows if actflg="1" is found...)

<task Col="6" Object="ABCD">
<task Col="7" Object="ABCDE">


推荐答案

您可以使用 grep - B XX ,在匹配行之前打印XX行。然后你使用 head -1 来打印第一个:

You can use grep -B XX, which print XX lines before matching lines. Then you use head -1 to just print the first one:

$ grep -B2 -i 'actflg="1"' file
<task Col="6" Object="ABCD">
<checkpoint TcpOn="0"/>
<after ActFlg="1"/>

$ grep -B2 -i 'actflg="1"' file | head -1
<task Col="6" Object="ABCD">






如果有多个匹配项,您可以执行:


In case there are multiple matches, you can do:

$ awk '/ActFlg="1"/ {print preprev} {preprev=prev; prev=$0}' file
<task Col="6" Object="ABCD">
<task Col="7" Object="ABCDE">



说明




  • '/ ActFlg =1/ {print preprev} 匹配包含 ActFlg =1的行,打印 preprev ,一条存储的行。
  • {preprev = prev; prev = $ 0} 这会保存前两行。之前的2存储在 preprev 中,而前一个存储在 prev 中。因此,无论何时我们处于新行中时,都会进行更新。

  • Explanation

    • '/ActFlg="1"/ {print preprev} matches lines containing ActFlg="1" and does print preprev, a stored line.
    • {preprev=prev; prev=$0} this keeps storing the two previous lines. The 2 before is stored in preprev and the previous in prev. So whenever we are in a new line, this gets updated.
    • 这篇关于如果另一个grep匹配,则使用Unix Bash shell命令来grep一些文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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