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

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

问题描述

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



例如,这是服务器日志

  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.1404 -
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.1404 -

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

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

/ p>

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

我只想显示: hello ss



有没有什么办法可以做到这一点?

假设你有gnu grep,你可以使用perl风格的正则表达式做一个积极的倒车镜像:

  grep -oP'(?<?GET \s /)\ w +'文件

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

  sed -n'/^.* GET [ [:空间:]] \ {1,\} \ / \([-_ [:alnum:]] \ {1,\} \)。* $ /秒// \1 / p'文件

如果您恰好有gnu sed(如果您不有gnu grep但是有gnu sed),可以大大简化:

  sed -n'/^.*GET\\ \\\\\\\\\\\\\\\(\\\\\\\\\\\\\\\\ \\ p> 

这里的底线是,你当然不需要管道来完成这个任务。 grep sed 就足够了。


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

For example, this is the server log

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 -

When I try with simple grep or awk,

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

it gives out

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 -

I just want to display : hello and ss

Is there any way this could be done?

解决方案

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

grep -oP '(?<=GET\s/)\w+' file

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

If you happen to have gnu sed (which would be odd if you don't have gnu grep but do have gnu sed), that can be greatly simplified:

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

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天全站免登陆