I have a log that contains lines from processes that handle authentications. Such an authentication usually consists of 4 lines. For example:
2022-09-21T00:02:45 [18633]: connection opened
2022-09-21T00:02:45 [3711]: connection opened
2022-09-21T00:02:45 [61811]: connection opened
2022-09-21T00:02:45 [9957]: connection opened
2022-09-21T00:02:46 [3711]: authentication attempt
2022-09-21T00:02:46 [61811]: authentication attempt
2022-09-21T00:02:49 [3711]: user FOO authentication failure
2022-09-21T00:02:51 [18633]: authentication attempt
2022-09-21T00:02:51 [9957]: authentication attempt
2022-09-21T00:03:01 [9957]: user QOZ authentication failure
2022-09-21T00:03:02 [3711]: connection closed
2022-09-21T00:03:34 [61811]: user BAR authentication success
2022-09-21T00:03:38 [61811]: connection closed
2022-09-21T00:03:45 [18633]: user BAZ authentication success
2022-09-21T00:03:45 [18633]: connection closed
2022-09-21T00:04:11 [9957]: connection closed
I would like to find all the logs that deal with a successful authentication. I can do this by finding the PIDs of those, and then grepping the file again for all lines that contain that PID:
for pid in $(cat log.txt | sed -En 's/.*\[([0-9]+)\].*success/\1/p'); do
grep $pid log.txt
done
This works:
2022-09-21T00:02:45 [61811]: connection opened
2022-09-21T00:02:46 [61811]: authentication attempt
2022-09-21T00:03:34 [61811]: user BAR authentication success
2022-09-21T00:03:38 [61811]: connection closed
2022-09-21T00:02:45 [18633]: connection opened
2022-09-21T00:02:51 [18633]: authentication attempt
2022-09-21T00:03:45 [18633]: user BAZ authentication success
2022-09-21T00:03:45 [18633]: connection closed
But it is very inefficient as there are many events, and I'm grepping the entire file for all of them. On a multi GB file this is undoable.
I'm looking for an alternative way to do this. Is there a way to (perhaps in awk?) to do something like this?
- Match lines with
authentication successand extract the PID - Search in the neighbourhood (say 10 lines before and after the match) for lines with that PID, and return all of them
many thx