我怎么可以检查一文件的大小和加入,结果在Excel电子表格在Perl?

StackOverflow https://stackoverflow.com/questions/71643

  •  09-06-2019
  •  | 
  •  

目前我监测特定文件有一个简单壳一衬:

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文件将使用 电子表格::Write.但如果你需要更新现有的Excel文件,你应该看看 电子表格::ParseExcel.

其他提示

你可以使用 -s 操作员 获得的文件的大小和 电子表格::ParseExcel电子表格::WriteExcel 模块,以产生一个更新的电子表格中的信息。 电子表格::ParseExcel::SaveParser 可以让你轻易地将两者结合,在情况需要更新现有的文件用新的信息。如果你是,你可能想要实现自动化Excel本身相反,可能的援助 Win32::OLE.

你也可以跳过麻烦的书写。xls格式文件,并使用一个更一般的(但充分Excel友好)的格式,如CSV:

#!/bin/bash
date=`date +%Y/%m/%d:%H:%M:%S`
size=$(ls -lah somefile |  awk '{print $5}')
echo "$date,$size"

然后,在你的务:

0 0 * * * /path/to/script.sh >/data/sizelog.csv

然后你进口。csv文件进的Excel就像任何其他电子表格。

Perl也具有非常不错(和非常 快速) 文字的::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

该模块你应该使用的是 电子表格::WriteExcel.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top