Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
568 views
in Technique[技术] by (71.8m points)

linux - Using grep to get the next WORD after a match in each line

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

grep -oP '(?<=GETs/)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, that can be greatly simplified:

sed -n '/^.*GETs+/(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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...