解析日志文件并转换为csv所需的脚本

时间:2014-03-16 18:29:50

标签: shell

我需要解析包含TOP命令输出的文本/日志文件,我需要解析并存储来自该命令的数据。日志文件具有以下格式(我可以使用任何脚本语言) -

top - 11:48:02 up 8 days, 15:49,  7 users,  load average: 0.05, 0.05, 0.00
Tasks:   1 total,   0 running,   1 sleeping,   0 stopped,   0 zombie
Cpu(s):  1.7%us,  1.9%sy,  0.1%ni, 96.4%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st
Mem:  198319908k total, 28256968k used, 170062940k free,   767436k buffers
Swap:        0k total,        0k used,        0k free, 23313752k cached

  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND                                                                           
28983 root      10 -10  373m  46m  27m S  2.0  0.0   0:26.10 ras                                                                               


top - 12:03:02 up 8 days, 16:04,  7 users,  load average: 1.24, 1.37, 0.81
Tasks:   1 total,   0 running,   1 sleeping,   0 stopped,   0 zombie
Cpu(s):  6.2%us,  2.7%sy,  0.1%ni, 91.0%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st
Mem:  198319908k total, 29182584k used, 169137324k free,   768524k buffers
Swap:        0k total,        0k used,        0k free, 24202460k cached

  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND                                                                           
28983 root      10 -10  387m  60m  29m S 79.0  0.0  12:17.57 ras                                                                               

top - 12:33:03 up 8 days, 16:34,  7 users,  load average: 0.56, 0.72, 0.73
Tasks:   1 total,   0 running,   1 sleeping,   0 stopped,   0 zombie
Cpu(s):  5.1%us,  2.5%sy,  0.1%ni, 92.3%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st
Mem:  198319908k total, 31074584k used, 167245324k free,   770688k buffers
Swap:        0k total,        0k used,        0k free, 26041508k cached

  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND                                                                        
28983 root      10 -10  396m  69m  29m S 57.6  0.0  31:32.00 ras

我想要格式为

的csv文件
[ top,time,CPU(% USER), CPU (%SYSTEM),Used Memory, PID, VIRT,RES,SHR,%CPU,%MEM,ProcessName]

以下是上述日志文件的示例 -

top,11:48:02,1.7%us,1.9%sy,28256968k,28983,373m,46m,27m,2.0,0.0,ras
top,12:03:02,6.2%us,2.7%sy,29182584k,28983,387m,60m,29m,79.0,0.0,ras
top,12:33:03,5.1%us,2.5%sy,31074584k,28983,396m,69m,29m,57.6,0.0,ras

此致

1 个答案:

答案 0 :(得分:0)

这可能是您使用awk可以做的最简单的解决方案之一:

$ awk '
/^top/ { printf "%s,%s,",$1,$3 }
/^Cpu/ { printf "%s%s",$2,$3 }
/^Mem/ { printf "%s,",$4 }
/^ *PID/ { getline; printf "%s,%s,%s,%s,%s,%s,",$1,$5,$6,$7,$9,$10; print $NF }' logfile
top,11:48:02,1.7%us,1.9%sy,28256968k,28983,373m,46m,27m,2.0,0.0,ras
top,12:03:02,6.2%us,2.7%sy,29182584k,28983,387m,60m,29m,79.0,0.0,ras
top,12:33:03,5.1%us,2.5%sy,31074584k,28983,396m,69m,29m,57.6,0.0,ras