I need to match ‘HTTP 1.1’ string in access.log file and print next field to it which may be 200, 504 (HTTP status) code. How do I do it in awk?
My http log format is:
log_format debuglogformat '[$time_local] $remote_addr - $remote_user - $server_name $host to: $upstream_addr: $request $status upstream_response_time $upstream_response_time msec $msec request_time $request_time';
Log file entry:
[19/May/2023:19:32:56 +0000] 172.16.13.100 - - - www.example.com www.example.com to: 10.14.1.42:80: GET /product/id_253535/ HTTP/1.1 200 upstream_response_time 0.340 msec 1684524776.855 request_time 0.343
[19/May/2023:19:34:34 +0000] 172.16.13.100 - - - www.example.com www.example.com to: 10.14.1.42:80: GET /media/asset/images/logo.png HTTP/1.1 200 upstream_response_time 0.340 msec 1684524776.855 request_time 0.343
How do I do it?
Try awk loop over the fields for a match HTTP/1.1
, and print the next record using $i+1
awk '{ for(i=1; i<=NF; i++) { if($i == "HTTP/1.1") { print $(i+1); break; } } }' /path/to/filename.log
OR
awk '{ for(i=1; i<=NF; i++) { if($i == "HTTP/1.1")
{ print $(i+1); break; } } }' /path/to/filename.log
The awk start with a for loop that iterates over each field ($i
) in a line and if the field matched HTTP/1.1
, it prints the value of next the next column ($(i+1)
) and breaks out of the loop. It reads data from the /path/to/filename.log
file.
AWK printing next record following matched record
The following will print all lines when HTTP/1.1 200 status code not found:
awk '{ for(i=1; i<=NF; i++) { if($i == "HTTP/1.1") { if ( $(i+1) != 200) print $0; break; } } }' /path/to/filename.log
And this one only print HTTP/1.1 504 entries (match for 504 HTTP status code):
awk '{ for(i=1; i<=NF; i++) { if($i == "HTTP/1.1") { if ( $(i+1) == 504) print $0; break; } } }' /path/to/filename.log
For more info read the awk man page using man command:
man awk
1 Like
Perfect. Also, check like ($i+1) != 200
and print $0
provided me exact info I needed. I used grep command but it was matching some data:
``
grep ‘HTTP/1.1 200’ access_log
AWK just good.