파일 크기를 확인하고 그 결과를 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 파일을 작성하는 간단한 방법은 다음과 같습니다.스프레드시트::쓰기.하지만 기존 Excel 파일을 업데이트해야 하는 경우 다음 사항을 살펴봐야 합니다.스프레드시트::ParseExcel.
다른 팁
당신이 사용할 수있는 그만큼 -s
운영자 파일의 크기와 정보를 얻으려면 스프레드시트::ParseExcel 그리고 스프레드시트::WriteExcel 정보가 포함된 업데이트된 스프레드시트를 생성하는 모듈입니다. 스프레드시트::ParseExcel::SaveParser 기존 파일을 새로운 정보로 업데이트하려는 경우 두 가지를 쉽게 결합할 수 있습니다.Windows를 사용하는 경우 대신 Excel 자체를 자동화할 수 있습니다. Win32::OLE.
.xls 형식 파일을 작성하는 번거로움을 건너뛰고 CSV와 같은 보다 일반적인(그러나 충분히 Excel 친화적인) 형식을 사용할 수도 있습니다.
#!/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은 또한 매우 좋은(그리고 매우 빠른) 텍스트::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.