简体   繁体   中英

python - How to grep for numbers from log file and do summing

I have a log file with the following strings:

2013-09-10 12:29:06 C9 T3 Update:555 Interfaces: 100 nodes: 0 ports: 0 flows: 106677
2013-09-10 12:30:07 C9 T3 Update:555 Interfaces: 100 nodes: 0 ports: 0 flows: 106281
2013-09-10 12:31:07 C9 T3 Update:555 Interfaces: 100 nodes: 0 ports: 0 flows: 108252
2013-09-10 12:32:06 C9 T3 Update:555 Interfaces: 100 nodes: 0 ports: 0 flows: 106650
2013-09-10 12:33:05 C9 T3 Update:555 Interfaces: 100 nodes: 0 ports: 0 flows: 49734

I would like to write a script to read through the file and grep only for the # of flows (eg 106677) and then do a sum on them. Any ideas on best approach? I should first try to strip only the # of flows and write to a file and then do sum?

What about using csv module:

import csv

with open('logfile') as f:
    reader = csv.reader(f, delimiter=" ")
    print sum(int(line[-1]) for line in reader)

prints: 477594 for your example data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM