如何Grep多行以获取所有线程内容

时间:2018-11-23 07:39:33

标签: regex unix grep

如何Grep多行以获取该线程下的所有行。 我已经尝试过grep -A,-B,-C,但这似乎比我需要的多或少。

$cat text.txt
=====================================================================
[11-23-18 10:07:01:119]::Thread(ABC):request returned

[11-23-18 10:07:01:120]::Thread(ABC):Sending packet 'POST /aq/ConManager HTTP/1.1
Host: localhost:192.168.1.1
User-Agent: gSOAP/2.7
Content-Type: text/xml; charset=utf-8
Content-Length: 1149
Connection: keep-alive
Accept-Encoding: gzip, deflate
SOAPAction: ""

[11-23-18 10:07:01:121]::Thread(XYZ): doing request

[11-23-18 10:07:01:122]::Thread(XYZ): request returned

================================================================

现在,如果我使用grep -A 10 ABC text.txt,它将输出所有其他行,例如thread XYZ。我只想输出所有的ABC线程及其行,并且如果我仅使用grep,它将不会在ABC线程之后输出后续行。

2 个答案:

答案 0 :(得分:1)

您可以使用

awk '/^\[[^][]*]::Thread\(ABC\)/,/^$/' file > newfile

它匹配两个模式之间的一行线,第二个匹配空行,第一个匹配:

  • ^-一行的开头
  • \[-一个[
  • [^][]*-除[]以外的0多个字符
  • ]-一个]
  • ::Thread\(ABC\)-一个::Thread(ABC)子字符串

请参见online demo

答案 1 :(得分:1)

这里可能是您想要的东西,或者可能不是您想要的东西

$ awk -v RS="" '/ABC/' file

输出:

=====================================================================
[11-23-18 10:07:01:119]::Thread(ABC):request returned
[11-23-18 10:07:01:120]::Thread(ABC):Sending packet 'POST /aq/ConManager HTTP/1.1
Host: localhost:192.168.1.1
User-Agent: gSOAP/2.7
Content-Type: text/xml; charset=utf-8
Content-Length: 1149
Connection: keep-alive
Accept-Encoding: gzip, deflate
SOAPAction: ""

解释:

$ awk -v RS="" '  # use empty records as record separators
/ABC/             # if there is ABC in the record, print it
' file