Parsing the output of "uptime" with bash
Posted
by
Keek
on Super User
See other posts from Super User
or by Keek
Published on 2014-08-23T06:57:35Z
Indexed on
2014/08/23
10:24 UTC
Read the original article
Hit count: 560
I would like to save the output of the uptime
command into a csv file in a Bash script. Since the uptime
command has different output formats based on the time since the last reboot I came up with a pretty heavy solution based on case
, but there is surely a more elegant way of doing this.
uptime output:
8:58AM up 15:12, 1 user, load averages: 0.01, 0.02, 0.00
desired result:
15:12,1 user,0.00 0.02 0.00,
current code:
case "`uptime | wc -w | awk '{print $1}'`" in
#Count the number of words in the uptime output
10)
#e.g.: 8:16PM up 2:30, 1 user, load averages: 0.09, 0.05, 0.02
echo -n `uptime | awk '{ print $3 }' | awk '{gsub ( ",","" ) ; print $0 }'`","`uptime | awk '{ print $4,$5 }' | awk '{gsub ( ",","" ) ; print $0 }'`","`uptime | awk '{ print $8,$9,$10 }' | awk '{gsub ( ",","" ) ; print $0 }'`","
;;
12)
#e.g.: 1:41pm up 105 days, 21:46, 2 users, load average: 0.28, 0.28, 0.27
echo -n `uptime | awk '{ print $3,$4,$5 }' | awk '{gsub ( ",","" ) ; print $0 }'`","`uptime | awk '{ print $6,$7 }' | awk '{gsub ( ",","" ) ; print $0 }'`","`uptime | awk '{ print $10,$11,$12 }' | awk '{gsub ( ",","" ) ; print $0 }'`","
;;
13)
#e.g.: 12:55pm up 105 days, 21 hrs, 2 users, load average: 0.26, 0.26, 0.26
echo -n `uptime | awk '{ print $3,$4,$5,$6 }' | awk '{gsub ( ",","" ) ; print $0 }'`","`uptime | awk '{ print $7,$8 }' | awk '{gsub ( ",","" ) ; print $0 }'`","`uptime | awk '{ print $11,$12,$13 }' | awk '{gsub ( ",","" ) ; print $0 }'`","
;;
esac
© Super User or respective owner