如何在同一日志文件中grep匹配分属不同行的指定多关键词?
Got it, let's tackle this problem. You need to pull out lines containing both checkCredit?msisdn=766117506 and creditLimit from the same log file, even if they're on separate lines. Here are a few practical approaches based on common log formats:
Method 1: Match Adjacent Request/Response Lines with Awk
If your log follows a pattern where the request line (with your target msisdn) is immediately followed by the response line (with creditLimit), awk is perfect for grabbing both lines in one go:
awk '/checkCredit\?msisdn=766117506/{print; getline; print}' your_log_file.log
How it works:
- When
awkfinds a line matching your target msisdn string, it first prints that request line. - The
getlinecommand reads the next line (your response line withcreditLimit), which we then print as well.
Method 2: Use Grep Context for Known Line Intervals
If you know the maximum number of lines between your target request and the corresponding creditLimit line, use grep's context flags:
For example, if the response line is always 1 line after the request:
grep -A 1 "checkCredit\?msisdn=766117506" your_log_file.log
To filter out any extra lines and only keep the ones with your two keywords:
grep -A 1 "checkCredit\?msisdn=766117506" your_log_file.log | grep -E "checkCredit\?msisdn=766117506|creditLimit"
Method 3: Precise Matching with Transaction ID
Looking at your log sample, there's a transid field that uniquely identifies each request-response pair. This is the most reliable method if requests and responses aren't strictly adjacent:
- First, extract the transaction ID for your target request:
TARGET_TRANSID=$(grep "checkCredit\?msisdn=766117506" your_log_file.log | grep -o "transid=[0-9]*" | cut -d= -f2)
- Then use this ID to fetch both the request and its corresponding response:
grep -E "checkCredit\?msisdn=766117506|$TARGET_TRANSID.*creditLimit" your_log_file.log
This ensures you're getting exactly the right response for your specific request, even if other log lines are in between.
内容的提问来源于stack exchange,提问作者mahesh

