Shell Script – How to Sum Values and Calculate Average Between Patterns

awksedshell-scripttext processing

I have a huge text file, each line contains value or text pattern.

How can I find average or at least sum values between each pattern?

Are there any awk/sed or maybe perl solutions?

Example:

pattern1
200
300
pattern2
200
100
200
pattern3
pattern4

Expected output:

pattern1
250
pattern2
166
pattern3
pattern4

Best Answer

Awk approach:

awk '/pattern/{ if (cnt) { printf "%d\n", sum/cnt; sum=cnt=0 } print }
     /^[0-9]+$/{ sum += $1; cnt++ }' file

The output:

pattern1
250
pattern2
166
pattern3
pattern4
Related Question