我想我到处都是,我运气不好。我正在尝试创建一个简单的自动结算报告。我需要创建一个包含3列的CSV。像这样
Folder Size Billing Code
Folder1 300M XXXXX
Folder2 600M XXXXX
Folder3 200M XXXXX
我可以获得du -sh
并使用awk
来安排我想要的方式,并且我得到了大部分我正在尝试做的事情。但是我不知道如何在每列之前创建标题。我在bash,perl和python中寻找方法并且成功有限。如果我能弄清楚如何制作列标题标签,我想我会在那里做得很好。
答案 0 :(得分:4)
在Python中尝试csv module。具体来说,你需要writeheader()方法,它非常简单。
或者,如果您已经在shell脚本中执行此操作,为什么不首先将标题行回显到文件,然后确保后续命令使用追加运算符(>>)?
答案 1 :(得分:4)
在渲染值后添加名称怎么样?
$ sed 1i"This is the first line" - < /proc/loadavg
This is the first line
3.14 3.48 3.58 2/533 17661
答案 2 :(得分:1)
使用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
}
}
这样就可以在没有像du这样的外部命令的情况下写入CSV文件并在每个平台上运行 另请查看Perl的CSV模块以获取更多选项