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

如何基于现有grep/awk代码从日志文件提取数值并计算差值?

Solution to Calculate Pair-wise Start/End Differences

Great question! Instead of chaining separate grep and awk commands, we can handle the entire logic in a single awk script that processes your log file in one pass, tracks pairs of start/end values, and outputs the required differences cleanly.

The Command

awk '/start/i { start[++group_num] = $3 } /end/i { end[group_num] = $3 } END { for (i=1; i<=group_num; i++) printf "difference%d : %d\n", i, end[i] - start[i] }' logs.txt

How It Works

Let’s break down each part to make it clear:

  • /start/i { start[++group_num] = $3 }: When we hit a line containing "start" (case-insensitive, matching your original grep -i), we store the 3rd field (your numeric value) in the start array, and increment our group counter to keep pairs aligned.
  • /end/i { end[group_num] = $3 }: When we hit a line containing "end" (also case-insensitive), we store the 3rd field in the end array using the same group counter—this ensures each end value is paired with the most recent start value.
  • END { ... }: After processing all lines in the log, we loop through each group, calculate the difference between the end and start values, and print it in your requested differenceN : X format.

Test Example

If your logs.txt looks like this:

start_value : 10
end_value : 30
start_value : 20
end_value : 50
start_value : 7
end_value : 12

Running the command will output:

difference1 : 20
difference2 : 30
difference3 : 5

Notes

  • This assumes your start/end pairs are in order (each start is followed by its corresponding end). If pairs are out of order, you’d need a more complex script to match values by an identifier, but based on your example, this should work perfectly.
  • The /i flag makes pattern matching case-insensitive, just like your original grep -i commands. If you don’t need case insensitivity, you can remove the i (e.g., /start/ instead of /start/i).
  • Any lines in the log that don’t match "start" or "end" are ignored automatically—no extra filtering needed.

内容的提问来源于stack exchange,提问作者KaverappaKU

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:32:54