目前,我使用简单的 shell 单线监视特定文件:
filesize=$(ls -lah somefile | awk '{print $5}')
我知道 Perl 有一些很好的模块来处理 Excel 文件,所以我们的想法是,比如说,每天运行检查,也许使用 cron,然后将结果写入电子表格以供进一步统计使用。
您可以使用运算符获取-s
文件的大小,并使用Spreadsheet::ParseExcel和Spreadsheet::WriteExcel模块生成包含信息的更新电子表格。Spreadsheet::ParseExcel::SaveParser让您可以轻松地将两者结合起来,以防您想用新信息更新现有文件。如果您在 Windows 上,您可能想要自动化 Excel 本身,可能借助Win32::OLE。
您可以使用 -s 运算符检查文件的大小。
使用严格; 使用警告; 使用 File::Slurp qw(read_file write_file); 使用电子表格::ParseExcel; 使用电子表格::ParseExcel::SaveParser; 使用电子表格::WriteExcel; 我的 $file = 'path_to_file'; 我的 $size_file = 'path_to_file_keeping_the_size'; 我的 $excel_file = 'path_to_excel_file.xls'; 我的 $current_size = -s $file; 我的 $old_size = 0; 如果(-e $size_file){ $old_size = read_file($size_file); } if ($old_size new; 我的 $excel = $parser->Parse($excel_file); 我的 $row = 1; $row++ while $excel->{Worksheet}[0]->{Cells}[$row][0]; $excel->AddCell(0, $row, 0, 标量(本地时间)); $excel->AddCell(0, $row, 1, $current_size); 我的 $workbook = $excel->SaveAs($excel_file); $工作簿->关闭; } 别的 { 我的 $workbook = Spreadsheet::WriteExcel->new($excel_file); 我的 $worksheet = $workbook->add_worksheet(); $worksheet->write(0, 0, '日期'); $worksheet->write(0, 1, '大小'); $worksheet->write(1, 0, 标量(本地时间)); $worksheet->write(1, 1, $current_size); $工作簿->关闭; } } write_file($size_file, $current_size);
编写 Excel 文件的一种简单方法是使用 Spreadsheet::Write。但是如果您需要更新现有的 Excel 文件,您应该查看 Spreadsheet::ParseExcel。
您还可以跳过编写 .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
您应该使用的模块是Spreadsheet::WriteExcel。