如何检查文件大小并将结果添加到Perl的Excel电子表格中?
时间:2020-03-05 18:55:45 来源:igfitidea点击:
目前,我使用简单的shell一线式监视特定文件:
filesize=$(ls -lah somefile | awk '{print }')
我知道Perl有一些很好的模块来处理Excel文件,所以我们的想法是每天(可能是使用cron)运行该检查,并将结果写在电子表格中以供进一步统计使用。
解决方案
回答
我们可以使用-s运算符来获取文件的大小,并使用Spreadsheet :: ParseExcel和Spreadsheet :: WriteExcel模块来生成带有信息的更新电子表格。 Spreadsheet :: ParseExcel :: SaveParser可让我们轻松地将两者结合起来,以防我们想用新信息更新现有文件。如果我们使用的是Windows,则可能希望借助Win32 :: OLE来自动执行Excel本身。
回答
我们应该使用的模块是Spreadsheet :: WriteExcel。
回答
我们可以使用-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。
回答
我们也可以跳过编写.xls格式文件的麻烦,而使用更通用(但对Excel足够友好)的格式,例如CSV:
#!/bin/bash
date=`date +%Y/%m/%d:%H:%M:%S`
size=$(ls -lah somefile | awk '{print }')
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

