如何在awk中将输出变为变量。
当前输出
cat ii
Iie:573T
Eed:448.0T
vail:74T
必需的输出
Total Size : 573 TB
Total Used : 448.0 TB
Avilable : 74 TB
Used (%) : 86.10% # Total Used(%) = Total Used/Total Size *100 = 86.1(%)
错误脚本无效。
cat ii | awk ' /Size:/ {total_size=$NF}
> /Used:/ { total_used=$NF }
> END{
TotalUsed= total_size=total_used
print "Total Used="TotalUsed}'
答案 0 :(得分:1)
要获得您需要的86.1%
, Eed 至少为493.353
见:
$ awk 'BEGIN{printf "%f\n", 86.1*573/100}'
493.353000
$ awk 'BEGIN{printf "%f\n", 493.353/573*100}'
86.100000
以下是打印已修改标头和百分比
的一种方法awk 'BEGIN{
OFS=FS=":";
h["Iie"]="Total Size";
h["Eed"]="Total Used";
h["vail"]="Avilable"
}
$1 in h{
sub(/T/," TB",$2);
print h[$1], $2;
h[$1]=$2
}
END{
print "Used (%)",h["Eed"]/h["Iie"]*100
}
' infile
输入:
$ cat infile
Iie:573T
Eed:448.0T
vail:74T
输出:
$ awk 'BEGIN{OFS=FS=":";h["Iie"]="Total Size";h["Eed"]="Total Used";h["vail"]="Avilable"}$1 in h{sub(/T/," TB",$2);print h[$1],$2; h[$1]=$2 }END{print "Used (%)",h["Eed"]/h["Iie"]*100}' infile
Total Size:573 TB
Total Used:448.0 TB
Avilable:74 TB
Used (%):78.185
<强>解释强>
awk 'BEGIN{
OFS=FS=":"; # i/p and o/p field sep
h["Iie"]="Total Size"; # array of key and values
h["Eed"]="Total Used";
h["vail"]="Avilable"
}
$1 in h{ # if its of our interest and in array h
# not really necessary,
# in current context
# skips saving any unwanted column in array h
sub(/T/," TB",$2); # substiute T with space and TB
# can also be " &B"
print h[$1], $2; # print corresponding header and 2nd field
h[$1]=$2 # we are done save value
}
END{
# calculate percentage from saved value
#
print "Used (%)",h["Eed"]/h["Iie"]*100
}
' infile
答案 1 :(得分:0)
请尝试关注awk
并告诉我这是否对您有所帮助。
awk -F":" '
/Iie/{
total_size=$2+0;
next
}
/Eed/{
total_used=$2+0;
next
}
/vail/{
Avilable=$2+0;
next
}
END{
print "Total Size :",total_size" TB" RS \
"Total Used :",total_used" TB" RS "Avilable :"\
,Avilable" TB" RS "Used (%) :",(total_used/total_size)*100"%"
}' Input_file