Output sar command results to a csv file

Agi picture Agi · Mar 11, 2013 · Viewed 21k times · Source

I'm relatively new to shell programming and would like to know if there is a simple way to output the results of the sar command to a csv file. Using sar > file1.csv does the job, but it is not properly formatted. All the data is present in one column. I tried this, but it was worse

sar -d -u -w 1 1 | grep -v Average | grep -v Linux | tr -s ' ' ',' | tr -d '\n' > file1.csv

Can anyone give me the right script to store the output of the sar command in a csv file. Help will be appreciated.

Answer

mimsugara picture mimsugara · Jun 13, 2014

I know this is kind of old but you should, or could, use sadf -dh -- <sar command>. It is part of the sysstat package and it will give you the csv output without any need for awk and regex. Actually, the latest versions are also able to output the info to JSON and XML. You can just pick your poison :)

Simple example:

$ sadf -dh -- -p
localhost.localdomain;-1;2014-06-13 08:47:02 UTC;LINUX-RESTART
# hostname;interval;timestamp;CPU;%user;%nice;%system;%iowait;%steal;%idle[...]
localhost.localdomain;600;2014-06-13 09:00:01 UTC;-1;8.80;0.01;1.65;9.51;0.00;80.03
localhost.localdomain;600;2014-06-13 09:10:01 UTC;-1;3.03;0.71;2.41;0.81;0.00;93.05