【问题标题】:Folder Size Report to CSV文件夹大小报告到 CSV
【发布时间】:2012-12-19 11:18:09
【问题描述】:
我想我到处都看过,但运气不佳。我正在尝试创建一个简单的自动计费报告。我需要创建一个包含 3 列的 CSV。像这样
Folder Size Billing Code
Folder1 300M XXXXX
Folder2 600M XXXXX
Folder3 200M XXXXX
我可以得到一个du -sh 并使用awk 来安排我想要的方式,并且我得到了我想要做的大部分事情。但是我不知道如何在每列之前创建一个标题。我在 bash、perl 和 python 中寻找方法,但成功有限。如果我能弄清楚如何制作列标题标签,我想我会很好。
【问题讨论】:
标签:
python
perl
bash
csv
du
【解决方案1】:
试试 Python 中的csv module。具体来说,您需要 writeheader() 方法,它非常简单。
或者,如果您已经在 shell 脚本中执行此操作,为什么不先将标题行回显到文件中,然后确保后续命令使用附加运算符 (>>)?
【解决方案2】:
在渲染值之后添加名称怎么样?
$ sed 1i"This is the first line" - < /proc/loadavg
This is the first line
3.14 3.48 3.58 2/533 17661
【解决方案3】:
perl 的一种方法:
#!/usr/bin/perl
use strict;
use warnings;
use File::Find;
open my $fh, '>:encoding(utf8)','your outfile.csv';
# write the first line with the column names
print $fh "Folder,Size,Billing Code\n";
# Do your folder calculations
my $dirpath = "/your/path";
my $bytes;
find(\&folders,$dirpath);
close $fh;
sub folders {
if (-d $_) {
$bytes = 0;
find(\&size,$_);
$bytes = $bytes/1_048_576; # Convert Bytes to Mega Bytes
print $fh $_.",".$bytes."M,your_billing_code \n";
}
}
sub size {
if(-f $_){
$bytes += -s _; # This is not a typo
# -X _ does a filesystem operation on the
# last used stat structure
# this saves new filesystem calls and therefore performance
# see http://perldoc.perl.org/functions/-X.html for more info
}
}
这会写入 CSV 文件而无需像 du 这样的外部命令,并且适用于每个平台。
另请查看 Perl 的 CSV 模块以获取更多选项