0

I have a file in format like this:

method1|duration=300s
method2|duration=300s
method1|duration=500s
method1|duration=300s
method1|duration=700s
method3|duration=300s
...

How can I get the average duration time of method1 using Linux Shell? Thanks.

3 Answers 3

2

Use this:

awk -F'[=s]' '/method1/{t+=$2;c++}END{printf "%ss\n",t/c}' file

-F[=s] sets the field delimiter to = or s making it easy to extract the numerical value between them. t+=$2 will add the numerical value to the total t. c++ will count the lines containing the term method1. After the last line of input has been processed END, we print the total t divided by c, the number of lines containing method1.

Note: Initialization of the variables c and t is not necessary since awk initializes them with 0 on their first usage.

Sign up to request clarification or add additional context in comments.

1 Comment

would be good if you add a selection on method1 (required in the question) and average on this only: awk -F'[=s]' '/method1/{s+=$2;count+=1}END{print s/count}'
0

You can use awk for that. If duration is always in seconds something like this should work:

awk -F '\\||=' 'BEGIN { sum = 0; rows = 0 } { if ($1 == "method1") { sum += $3; rows += 1; } } END { print sum / rows "s" }' data_file

Comments

0

Using awk you can do it as:

awk -F '[=s]' 'BEGIN{count=0;sum=0} /method1/{sum+=$2;count+=1} END{print sum/count}' filename

All the duration must be of same time unit.

This will initially set count to 0 and sum to 0. During each iteration, sum will get added and count will be incremented if method1 is found in the line. At the end, sum/count will be printed out.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.