cybodroid cybodroid - 26 days ago 10
Bash Question

How can I modify following ps command to print in comma separated value (CSV) format?

I have following command:

ps -e -o pcpu,pmem,args,pid --sort=pcpu | sed '5q' | awk ' {print $1,$2,$3,$4 }'


Its output is:

%CPU %MEM COMMAND PID
0.0 0.1 /sbin/init 1
0.0 0.0 [kthreadd] 2
0.0 0.0 [ksoftirqd/0] 3
0.0 0.0 [kworker/0:0H] 5


how can I modify my original command given above to print out in csv format like as shown below:

%CPU, %MEM, COMMAND, PID
0.0, 0.1, /sbin/init, 1
0.0, 0.0, [kthreadd], 2
0.0, 0.0, [ksoftirqd/0], 3
0.0, 0.0, [kworker/0:0H], 5

Answer

Usa an Output Field Separator (OFS). Add OFS=", "; to your awk command:

ps -e -o pcpu,pmem,args,pid --sort=pcpu | sed '5q' | awk ' {OFS=", "; print $1,$2,$3,$4 }'

or shorter:

ps -e -o pcpu,pmem,args,pid --sort=pcpu | awk 'NR<=5 {OFS=", "; print $1,$2,$3,$4 }'

Output (example):

%CPU, %MEM, COMMAND, PID
0.0, 0.0, [migration/0], 6
0.0, 0.0, [migration/1], 7
0.0, 0.0, [migration/2], 11
0.0, 0.0, [migration/3], 14

See: 8 Powerful Awk Built-in Variables – FS, OFS, RS, ORS, NR, NF, FILENAME, FNR