2013-01-04 42 views
-2

我想我到處都看,我沒有太多的運氣。我正在嘗試創建一個簡單的自動帳單報告。我需要創建一個3列的CSV。這樣文件夾大小報告到CSV

Folder Size Billing Code 
Folder1 300M XXXXX 
Folder2 600M XXXXX 
Folder3 200M XXXXX 

我可以得到一個du -sh和使用awk安排呢我怎麼想,我得到最什麼,我試圖做的。但是我不知道如何在每一列之前創建一個標題。我在bash,perl和python中查找了方法,並且成功有限。如果我能弄清楚如何製作列標題標籤,我想我會很好。

回答

4

在Python中嘗試csv module。具體來說,您需要writeheader()方法,這非常簡單。或者,如果您已經在shell腳本中執行此操作,爲什麼不直接將標題行回顯到文件中,然後確保後續命令使用append運算符(>>)?

4

如何在渲染值後添加名稱?

$ sed 1i"This is the first line" - < /proc/loadavg 
This is the first line 
3.14 3.48 3.58 2/533 17661 
+0

嗯,短劃線可能是多餘的,但顯然它也適用於它(: – jary

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 
    } 
} 

此寫入CSV文件沒有像杜外部命令和工作的每一個平臺上。 同時檢查Perl的CSV模塊以獲取更多選項