You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Awk在日志中同时匹配日期与指定消息并输出结果

Fixing Your Awk Command to Filter Specific Log Entries

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's today variable into awk (we can also use direct substitution here for simplicity)
  • /Date: \['"$today"'\]/: Matches lines where the Date field 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_testListeningFn message
  • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:52:27