新手求助:如何从文件提取TIME_EXEC与TIME_FINISHED数值并加减
Hey there! As someone new to working with timestamp data in files, let's break this down step by step so you can easily compute the difference between TIME_EXEC and TIME_FINISHED values. We'll use simple command-line tools that are perfect for this kind of task—no fancy programming required!
Method 1: One-Liner with Awk (Most Efficient)
Awk is ideal for parsing key-value pairs like your TIME_*=timestamp lines. This command will scan the file directly, capture the two values, and calculate their difference in one go:
awk -F'=' '/TIME_EXEC/{exec_time=$2} /TIME_FINISHED/{finish_time=$2} END{print "Time difference (seconds):", finish_time - exec_time}' your_file_name
Let me break this down for you:
-F'=': Sets the equal sign as the separator, so we can easily split each line into the key (likeTIME_EXEC) and its value (the timestamp)./TIME_EXEC/{exec_time=$2}: When we find a line withTIME_EXEC, we store the timestamp value in a variable calledexec_time./TIME_FINISHED/{finish_time=$2}: Similarly, we store theTIME_FINISHEDtimestamp infinish_time.END{...}: After scanning the entire file, we run this block to subtract the execution time from the finish time and print the result (since these are Unix timestamps, the difference will be in seconds).
Method 2: Combine Grep and Awk (If You Prefer Grep First)
If you're more comfortable using grep to first extract only the lines you care about, you can pipe that output to awk for the calculation:
grep -E "TIME_EXEC|TIME_FINISHED" your_file_name | awk -F'=' '{if($1=="TIME_EXEC") exec=$2; else finish=$2} END{print "Time difference (seconds):", finish - exec}'
grep -E "TIME_EXEC|TIME_FINISHED": Filters the file to only show lines containing either of those two keys.- The pipe (
|) sends that filtered output to awk, which then does the same value capture and calculation as the first method.
Handling Multiple Runs (If Your File Has Multiple Timestamp Pairs)
If your file contains multiple sets of TIME_EXEC and TIME_FINISHED (e.g., for different runs), you can modify the awk command to print the difference for each pair as it finds them:
awk -F'=' '/TIME_EXEC/{exec_time=$2} /TIME_FINISHED/{print "Run difference (seconds):", $2 - exec_time}' your_file_name
This will output a difference every time it encounters a TIME_FINISHED line, using the most recent TIME_EXEC value it found.
Quick Note
These timestamps are Unix epoch timestamps (count of seconds since January 1, 1970), so the difference you get will be in seconds. If you later want to convert that to a more readable format (like hours:minutes:seconds), you can use the date command with the difference value, but that's an extra step once you have the basic calculation down.
内容的提问来源于stack exchange,提问作者Ankit G

