目前我監視特定的文件,一個簡單的shell的一行:如何檢查文件大小並將結果添加到Perl的Excel電子表格中?
filesize=$(ls -lah somefile | awk '{print $5}')
我知道,Perl有一些不錯的模塊來處理Excel文件這樣的想法是,讓我們說,運行檢查每天,也許用cron,並將結果寫在電子表格中以供進一步統計使用。
目前我監視特定的文件,一個簡單的shell的一行:如何檢查文件大小並將結果添加到Perl的Excel電子表格中?
filesize=$(ls -lah somefile | awk '{print $5}')
我知道,Perl有一些不錯的模塊來處理Excel文件這樣的想法是,讓我們說,運行檢查每天,也許用cron,並將結果寫在電子表格中以供進一步統計使用。
您可以使用-s運算符檢查文件的大小。
use strict; use warnings; use File::Slurp qw(read_file write_file); use Spreadsheet::ParseExcel; use Spreadsheet::ParseExcel::SaveParser; use Spreadsheet::WriteExcel; my $file = 'path_to_file'; my $size_file = 'path_to_file_keeping_the_size'; my $excel_file = 'path_to_excel_file.xls'; my $current_size = -s $file; my $old_size = 0; if (-e $size_file) { $old_size = read_file($size_file); } if ($old_size new; my $excel = $parser->Parse($excel_file); my $row = 1; $row++ while $excel->{Worksheet}[0]->{Cells}[$row][0]; $excel->AddCell(0, $row, 0, scalar(localtime)); $excel->AddCell(0, $row, 1, $current_size); my $workbook = $excel->SaveAs($excel_file); $workbook->close; } else { my $workbook = Spreadsheet::WriteExcel->new($excel_file); my $worksheet = $workbook->add_worksheet(); $worksheet->write(0, 0, 'Date'); $worksheet->write(0, 1, 'Size'); $worksheet->write(1, 0, scalar(localtime)); $worksheet->write(1, 1, $current_size); $workbook->close; } } write_file($size_file, $current_size);
一種簡單的方式來寫Excel文件將使用 Spreadsheet::Write。 但如果您需要更新現有的Excel文件,您應該查看 Spreadsheet::ParseExcel。
我認爲我必須這樣做,首先創建電子表格,然後每天用新尺寸更新它。我可以問你,如果我不是UNIX管理員,並且我不能安裝新的,我怎麼能原則上處理這些模塊? – 2008-09-16 13:41:03
也許創建一個CSV文件比較容易。這些可以通過Excel加載,並且可以使用Perl輕鬆生成,無需額外的模塊。 – 2008-09-16 13:45:34
您可以使用the -s
operator獲取文件的大小,使用Spreadsheet::ParseExcel和Spreadsheet::WriteExcel模塊生成包含該信息的更新電子表格。 Spreadsheet::ParseExcel::SaveParser可讓您輕鬆地將兩者結合起來,以防您想用新信息更新現有文件。如果您使用的是Windows,則可能需要使用Excel本身自動化,可能需要藉助Win32::OLE。
您應該使用的模塊是Spreadsheet::WriteExcel。
您也可以跳過的寫作.xls格式文件的麻煩,並使用更通用的(但足夠的Excel友好的)格式,如CSV:
#!/bin/bash
date=`date +%Y/%m/%d:%H:%M:%S`
size=$(ls -lah somefile | awk '{print $5}')
echo "$date,$size"
然後,在你的crontab:
0 0 * * * /path/to/script.sh >/data/sizelog.csv
然後,您將該.csv文件導入到Excel中,就像任何其他電子表格一樣。
Perl中也有很不錯(和非常快)Text::CSV_XS,讓您可以輕鬆地使Excel友好的CSV文件,這可能是比創建正確的XLS文件更好的解決方案。
例如(過評論的指導值):
#!/usr/bin/perl
package main;
use strict; use warnings; # always!
use Text::CSV_XS;
use IO::File;
# set up the CSV file
my $csv = Text::CSV_XS->new({eol=>"\r\n"});
my $io = IO::File->new('report.csv', '>')
or die "Cannot create report.csv: $!\n";
# for each file specified on command line
for my $file (@ARGV) {
unless (-f $file) {
# file doesn't exist
warn "$file doesn't exist, skipping\n";
next;
}
# get its size
my $size = -s $file;
# write the filename and size to a row in CSV
$csv->print($io, [ $file, $size ]);
}
$io->close; # make sure CSV file is flushed and closed
你的問題是什麼呢? – 2008-09-16 12:25:04
我認爲問題是,你能爲我做這個嗎? :D – 2008-09-16 14:29:06