perl如何读取文件夹中的多个.txt文件?

时间:2016-05-12 05:27:40

标签: perl

我想问一下如何使perl脚本能够在文件夹中运行多个文本文件?

目前我需要在$目录中键入文件名以运行脚本。但是,当我想运行更多文件时,我需要始终更改$目录文件名。

如果我在同一个文件夹中有5个文件,有没有更简单的方法来完成它。非常感谢。

#!/usr/bin/env perl

use strict;
use warnings 'all';

my $directory = 'C:\Users\abc.txt.log';
my $testna    = 'nomv_deepsleep current';
my $testpin   = 'AFE_PMU_I_VDDLDO_1P8_EXT';

my @header = (
    'Unit#',        'Test_Name', 'Pin_Name', 'Low_limit',
    'Measure_Data', 'High_limit'
);
my $format = "%-8s %-30s %-40s %-15s %-15s %-s\n";
my $unit;

my $outfile = "$directory.sdc";

open( OUT, "> $outfile" );
open( INF, "$directory" )
    || die("\n ERROR, cannot open input file called: $directory\n ($!)\n\n");

printf $format, @header;
printf OUT $format, @header;

while (<INF>) {

    if (/Device#:\s*(\d+)/) {
        $unit = $1;
        next;
    }

    chomp;

    my @fields = split /\s{2,}/;

    if ( $fields[2] eq $testna and $fields[3] eq $testpin ) { # TEMP_SENSE_VBE

        printf $format, $unit, $fields[2], $fields[3], $fields[5],
            $fields[6], $fields[7];
        printf OUT $format, $unit, $fields[2], $fields[3], $fields[5],
            $fields[6], $fields[7];
    }

}
close(INF) || die "cannot close input file !!";
close(OUT);

2 个答案:

答案 0 :(得分:2)

尝试使用What is the fastest way to upload a big csv file in notebook to work with python pandas?

 while (my $directory = glob "C:/Users/*.txt")
{
   .. 
   ..

}

答案 1 :(得分:1)

只需将代码放入子例程中,并为glob

返回的每个值调用它

此代码需要将目录路径作为命令行上的参数,并处理在那里找到的所有.log个文件

例如,你会运行

perl myprog.pl C:\Users

查找并处理C:\Users\abc.txt.log以及以.log

结尾的任何其他文件
use strict;
use warnings 'all';
no warnings 'qw';

use File::Spec::Functions 'catfile';

use constant TESTNA  => 'nomv_deepsleep current';
use constant TESTPIN => 'AFE_PMU_I_VDDLDO_1P8_EXT';

my ($directory) = @ARGV;

process_file($_) for glob catfile($directory, '*.log');

my @header = qw/ Unit#  Test_Name  Pin_Name  Low_limit  Measure_Data  High_limit /;
my $format = "%-8s %-30s %-40s %-15s %-15s %-s\n";


sub process_file {
    my ($log_file) = @_;
    my $outfile = "$log_file.sdc";

    open my $inp_fh, '<', $log_file or die qq{\n ERROR, cannot open "$log_file" for input: $!\n\n};
    open my $out_fh, '>', $outfile  or die qq{\n ERROR, cannot open "$outfile" for output: $!\n\n};

    printf STDOUT  $format, @header;
    printf $out_fh $format, @header;

    my $unit;

    while ( <$inp_fh> ) {

        if (/Device#:\s*(\d+)/) {
            $unit = $1;
            next;
        }

        chomp;

        my @fields = split /\s{2,}/;

        if ( $fields[2] eq TESTNA and $fields[3] eq TESTPIN ) {    # TEMP_SENSE_VBE

            printf STDOUT  $format, $unit, @fields[ 2, 3, 5, 6, 7 ];
            printf $out_fh $format, $unit, @fields[ 2, 3, 5, 6, 7 ];
        }
    }
}