如何用Awk在日志中同时匹配日期与指定消息并输出结果
Hey there! Let's get that log filtering sorted out properly. Your current awk command is grabbing lines after any Date entry, but it's not checking for the current date or the specific message string you need. Here's how to fix it:
Step 1: Get the Current Date in the Right Format
First, we need to capture today's date in the same format as your logs (DD-MM-YYYY). Run this to store it in a shell variable:
today=$(date +"%d-%m-%Y")
Step 2: The Correct Awk Command
Use this command to filter logs that include today's date and the target message Upload_Msg_testListeningFn:
awk -v target_date="$today" ' /Date: \['"$today"'\]/ && /Message : .*Upload_Msg_testListeningFn/ ' /tmp/test.log > filtered_test.log
Let's Break This Down:
-v target_date="$today": Passes the shell'stodayvariable into awk (we can also use direct substitution here for simplicity)/Date: \['"$today"'\]/: Matches lines where theDatefield starts with today's date (the escaped brackets\[/\]match the literal brackets in your logs)&& /Message : .*Upload_Msg_testListeningFn/: Ensures the same line also contains the exact message string you're looking for> filtered_test.log: Redirects the matching lines to a new file (replace this with your desired output path)
Alternative (More Robust) Version
If you want to avoid escaping issues, use awk's index() function to check for the substrings:
today=$(date +"%d-%m-%Y") awk -v date="$today" -v msg="Upload_Msg_testListeningFn" ' index($0, "Date: [" date) != 0 && index($0, "Message : " msg) != 0 ' /tmp/test.log > filtered_test.log
Why Your Original Command Didn't Work
Your command awk '/^Date/{c=3} c&&c--' /tmp/test.log is designed to print the Date line plus the next 2 lines (since c starts at 3 and decrements each line). It doesn't:
- Check if the date is today's date
- Filter for the specific
Upload_Msg_testListeningFnmessage - Ensure the date and message are part of the same log entry
Test Example
If your log has these lines:
Date: [19-01-2018 21:09:40] Message : [batman error: Upload_Msg_testListeningFn]
Date: [18-01-2018 10:00:00] Message : [batman error: Upload_Msg_testListeningFn]
Date: [19-01-2018 22:00:00] Message : [robin info: Some_Other_Message]
When today is 19-01-2018, only the first line will be output to filtered_test.log.
内容的提问来源于stack exchange,提问作者Daya

