按用户/主机/工作区的总和结果分析文件



我有一个由另一个人的脚本生成的文件,它看起来像这样:(高度截断的示例)

Usage by user / host / workspace directory:
adallman:
  sideshow:
    bob               12065 MB
    mel                 488 MB
  simpsons:
    bart              32965 MB
afkham:
  simpsons:
    lisa             102466 MB
agnewjo:
  flanders:
    ned               70847 MB
    rod                2657 MB
ahoang:
  flanders:
    rod                2896 MB
akrishna:
  flanders:
    ned                3310 MB
  moes:
    barney             1850 MB
    carl              15674 MB
    lenny             10723 MB
  sideshow:
    bob                   0 MB
    mel              101700 MB
  simpsons:
    bart                  0 MB
    lisa                  0 MB

换句话说,用户在上面的文件中,我们可以解释我们所看到的,即

User:
  Host:
    Workspace: <size on that workspace MB>

我希望输出看起来像这样:(截断的)

adallman: <total in GB>
  afkham: <total in GB>
 agnewjo: <total in GB>
  ahoang: <total in GB>

我只想求出每个用户的总数。

记住,我可以总结创建这样的用户列表:

ypcat passwd | cut -d: -f1 > valid_users

并返回如下内容:(截断的)

zahrobsk
mylonopo
alindema
sutterk
sstslim
wleung
pazgil

这可以是一种方式:

$ awk '!/^ / {name=$1; next} NF==3{a[name]+=$2} END {for (i in a) print i, a[i]/1024, "GB"}' file
adallman: 44.4512 GB
ahoang: 2.82812 GB
afkham: 100.064 GB
akrishna: 130.134 GB
agnewjo: 71.7812 GB

解释

  • 它将那些不以空格开头的行作为用户名
  • 对于所有这些,它会不断添加第2列中的值
  • 最后,它打印结果除以1024,表示GB

纯bash解决方案(从stdin读取文件):

#!/bin/bash
valid_users=$( ypcat passwd | cut -d: -f1 )
declare -A sizes
while read username size foo
do
  if [ "$foo" = "MB" ]
  then
    let sizes[$username]=$(( sizes[$username] + $size ))
  fi
done
for i in $valid_users
do
  GB=$(( ${sizes[$i]:-0} / 1024 ))
  echo "$i: $GB"
done

最新更新