如何在shell脚本中将每日磁盘使用量导出为csv格式?

时间:2016-07-28 14:15:31

标签: linux shell csv diskspace

我的脚本如下。当我们运行脚本时,它会自动将磁盘空间使用量保存在单独的单元格中。

SIZES_1=`df -h | awk 'FNR == 1 {print $1","$2","$3","$4","$5","$6}'`
SIZES_2=`df -h | awk 'FNR == 2 {print $1","$2","$3","$4","$5","$6}'`
SIZES_3=`df -h | awk 'FNR == 3 {print $1","$2","$3","$4","$5","$6}'`
SIZES_4=`df -h | awk 'FNR == 4 {print $1","$2","$3","$4","$5","$6}'`
SIZES_5=`df -h | awk 'FNR == 5 {print $1","$2","$3","$4","$5","$6}'`
SIZES_6=`df -h | awk 'FNR == 6 {print $1","$2","$3","$4","$5","$6}'`
SIZES_7=`df -h | awk 'FNR == 7 {print $1","$2","$3","$4","$5","$6}'`
SIZES_8=`df -h | awk 'FNR == 8 {print $1","$2","$3","$4","$5","$6}'`
echo `date +%Z-%Y-%m-%d_%H-%M-%S` >>/home/jeevagan/test_scripts/sizes/excel.csv
echo "$SIZES_1" >> /home/jeevagan/test_scripts/sizes/excel.csv
echo "$SIZES_2" >> /home/jeevagan/test_scripts/sizes/excel.csv
echo "$SIZES_3" >> /home/jeevagan/test_scripts/sizes/excel.csv
echo "$SIZES_4" >> /home/jeevagan/test_scripts/sizes/excel.csv
echo "$SIZES_5" >> /home/jeevagan/test_scripts/sizes/excel.csv
echo "$SIZES_6" >> /home/jeevagan/test_scripts/sizes/excel.csv
echo "$SIZES_7" >> /home/jeevagan/test_scripts/sizes/excel.csv
echo "$SIZES_8" >> /home/jeevagan/test_scripts/sizes/excel.csv

这个脚本适用于我的机器。

我怀疑的是,如果其他人的机器有很多文件系统,我的脚本将无法获取所有文件系统的使用情况。如何让它自动抓住所有这些?

2 个答案:

答案 0 :(得分:2)

假设您需要所有文件系统,您可以将其简化为:

printf '%s\n' "$(date +%Z-%Y-%m-%d_%H-%M-%S)" >> excel.csv
df -h | awk '{print $1","$2","$3","$4","$5","$6}' >> excel.csv

答案 1 :(得分:0)

我会将其简化为

{ date +%Z-%F_%H-%M-%S; df -h | tr -s ' ' ','; } >> excel.csv
  • 分组命令,因此只需要一次重定向
  • 使用tr
  • 挤压空格并用一个逗号替换它们
  • 无需echo `date`或类似:它与date
  • 相同
  • date +%Y-%m-%ddate +%F
  • 相同

请注意,df -h的输出的第一行有一点缺陷,看起来像这样

Filesystem          Size  Used Avail Use% Mounted on

在最后一列的标题中有一个空格,因此它变为

Filesystem,Size,Used,Avail,Use%,Mounted,on

带一个额外的逗号。然而,最初的awk解决方案只是切断了该行的最后一个字。同样,路径中的空格会使这个解决方案绊倒。

要修复逗号问题,您可以运行

sed -i 's/Mounted,on$/Mounted on/' excel.csv

现在经常发生。

另外,要替换awk中的所有字段分隔符,而不是

awk '{print $1","$2","$3","$4","$5","$6}'

你可以使用

awk 'BEGIN { OFS = "," } { $1 = $1; print }'

或更短,

awk -v OFS=',' '{$1=$1}1'