regex group with multiple match with

时间:2015-07-30 18:06:19

标签: regex grep

需要编写正则表达式,以便 Resp Time:{{time}} 大于打印INFO直到Resp Time。

平台:使用grep -E,但如果你只提供正则表达式就可以了。

例如:

INFO 2015-07-30 06:50:48,208 Request: POST: /api/v1/jobs/
Request Data: {u'job_id': u'15488'}
Resp Status: 200
Resp Data: {'detail': 'ok'}
Resp Time: 1.0139939785004
INFO 2015-07-30 06:50:48,571 Request: POST: /api/v1/jobs/
Request Data: {u'job_id': u'15232 195049139026\r\n'}
Exception Raised: NOTFOUND
Resp Status: 200
Resp Data: {'detail': 'ok'}
Resp Time: 0.0570251941681
INFO 2015-07-30 06:50:48,571 Request: POST: /api/v1/jobs/
Request Data: {u'job_id': u'152195049139026\r\n'}
Exception Raised: NOTFOUND
Resp Status: 200
Resp Data: {'detail': 'ok'}
Resp Time: 1.0570251941681

在正则表达式之后,组将是:

INFO 2015-07-30 06:50:48,208 Request: POST: /api/v1/jobs/
Request Data: {u'job_id': u'15488'}
Resp Status: 200
Resp Data: {'detail': 'ok'}
Resp Time: 1.0139939785004
INFO 2015-07-30 06:50:48,571 Request: POST: /api/v1/jobs/
Request Data: {u'job_id': u'152195049139026\r\n'}
Exception Raised: NOTFOUND
Resp Status: 200
Resp Data: {'detail': 'ok'}
Resp Time: 1.0570251941681

2 个答案:

答案 0 :(得分:3)

您可以使用:

sed $'s/^INFO/\\\n&/' file | awk -v RS= 'match($0, "Resp Time: +(.+)", a) && a[1]>=1'

INFO 2015-07-30 06:50:48,208 Request: POST: /api/v1/jobs/
Request Data: {u'job_id': u'15488'}
Resp Status: 200
Resp Data: {'detail': 'ok'}
Resp Time: 1.0139939785004    
INFO 2015-07-30 06:50:48,571 Request: POST: /api/v1/jobs/
Request Data: {u'job_id': u'152195049139026\r\n'}
Exception Raised: NOTFOUND
Resp Status: 200
Resp Data: {'detail': 'ok'}
Resp Time: 1.0570251941681
  • sed $'s/^INFO/\\\n&/' file仅用于在INFO之前插入换行符。
  • awk命令使用null RS将每个INFO块拆分为单个记录。
  • match用于将Resp Time:文字后的部分与a[1]匹配。
  • a[1]>=1是检查响应时间是否为>= 1的简单条件。

更新:对于非gnu awk版本,您可以使用:

awk -F': ' '/^INFO /{a=$0;next} {a = a ORS $0} $1=="Resp Time" && $2>=1{print a}' file.log
INFO 2015-07-30 06:50:48,208 Request: POST: /api/v1/jobs/
Request Data: {u'job_id': u'15488'}
Resp Status: 200
Resp Data: {'detail': 'ok'}
Resp Time: 1.0139939785004
INFO 2015-07-30 06:50:48,571 Request: POST: /api/v1/jobs/
Request Data: {u'job_id': u'152195049139026\r\n'}
Exception Raised: NOTFOUND
Resp Status: 200
Resp Data: {'detail': 'ok'}
Resp Time: 1.0570251941681

答案 1 :(得分:2)

这里有一个命令/没有正则表达式的可能解决方案/:

cat filename |tr '\n' '@'|sed 's/INFO/\n&/g'|grep "Resp Time: 1"|sed 's/@/\n/g'