'bash script grep request path based on status code from api log
Hello I am new to bash scripting.
I have a line of text in a log file
9.0.100 - - [20/Feb/2020:12:00:00 +0000] "GET /file/one HTTP/1.1" 500 1024 "-" "Mozilla/5.0 (compatible)" "172.19.0.1"
I need the URL path /file/one if the status code is 500.
Any helpful resource?
Solution 1:[1]
If the file format is consistent and all the lines have the same fields you can use
awk -F'[" ]' '$11 == 500 {print $8}' < file.txt
Solution 2:[2]
Assuming you somehow read that log line into bash variable line, you could use this simple match to output desired info:
declare -r line='9.0.100 - - [20/Feb/2020:12:00:00 +0000] "GET /file/one HTTP/1.1" 500 1024 "-" "Mozilla/5.0 (compatible)" "172.19.0.1"';
if [[ "${line}" =~ \"([^\" ]+)[[:space:]]+([^\" ]+)[[:space:]]+([^\" ]+)\"[[:space:]]+([0-9]+) ]]; then
# declare -r method="${BASH_REMATCH[1]}"
# declare -r version="${BASH_REMATCH[3]}";
declare -r path="${BASH_REMATCH[2]}";
declare -r status="${BASH_REMATCH[4]}";
[[ "${status}" == "500" ]] && echo "${path}";
fi;
Surely you don't need to group other components like method or protocol version in the expression, but if just in case they're already grouped and assigned in commented out code to appropriate variables. Feel free to modify it as you wish.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Diego Torres Milano |
| Solution 2 | Cromax |
