在每行匹配后使用 grep 获取下一个 WORD [英] Using grep to get the next WORD after a match in each line

查看:14
本文介绍了在每行匹配后使用 grep 获取下一个 WORD的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的服务器日志中获取GET"查询.

I want to get the "GET" queries from my server logs.

例如,这是服务器日志

1.0.0.127.in-addr.arpa - - [10/Jun/2012 15:32:27] code 404, message File not fo$
1.0.0.127.in-addr.arpa - - [10/Jun/2012 15:32:27] "GET /hello HTTP/1.1" 404 -   
1.0.0.127.in-addr.arpa - - [10/Jun/2012 15:41:57] code 404, message File not fo$
1.0.0.127.in-addr.arpa - - [10/Jun/2012 15:41:57] "GET /ss HTTP/1.1" 404 -

当我尝试使用简单的 grep 或 awk 时,

When I try with simple grep or awk,

Adi:~ adi$ awk '/GET/, /HTTP/' serverlogs.txt

它发出

1.0.0.127.in-addr.arpa - - [10/Jun/2012 15:32:27] "GET /hello HTTP/1.1" 404 -
1.0.0.127.in-addr.arpa - - [10/Jun/2012 15:41:57] "GET /ss HTTP/1.1" 404 -

我只想显示:helloss

有什么办法可以做到吗?

Is there any way this could be done?

推荐答案

假设你有 gnu grep,你可以使用 perl-style regex 做一个积极的回顾:

Assuming you have gnu grep, you can use perl-style regex to do a positive lookbehind:

grep -oP '(?<=GETs/)w+' file

如果您没有 gnu grep,那么我建议您只使用 sed:

If you don't have gnu grep, then I'd advise just using sed:

sed -n '/^.*GET[[:space:]]{1,}/([-_[:alnum:]]{1,}).*$/s//1/p' file

如果你碰巧有 gnu sed,那可以大大简化:

If you happen to have gnu sed, that can be greatly simplified:

sed -n '/^.*GETs+/(w+).*$/s//1/p' file

这里的底线是,您当然不需要管道来完成此操作.grepsed 就足够了.

The bottom line here is, you certainly don't need pipes to accomplish this. grep or sed alone will suffice.

这篇关于在每行匹配后使用 grep 获取下一个 WORD的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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