使用perl帮助从同一文件名中提取文件的内容和值

时间:2010-12-10 18:04:37

标签: regex perl while-loop filehandle

很抱歉,如果这是详细的,但我有一个部分正常工作的perl脚本。我有一个正则表达式,它提取foo|bar和给定字符串的前缀。但问题是我的字符串也是FILE NAMES,我也想打开并检索其内容,如locale_col.dat.2010120813.png(参见下面的预期输出)。

输出现在看起来像这样:

Content:/home/myhome/col/.my_file_del.mail@locale.foo.org
Key1:foo:Key2:col
Content:/home/myhome/col/.my_file_del.dp1.bar.net
Key1:bar:Key2:col
Content:/home/myhome/jab/.my_file_del.mail@locale.foo.org
Key1:foo:Key2:jab
Content:/home/myhome/jab/.my_file_del.dp1.bar.net
Key1:bar:Key2:jab

我需要帮助调整这个,以便在一次传递中我可以读取字符串列表(文件名来自FileList.txt),从文件名路径中提取特定值(使用正则表达式)并打开其内容的文件名。我希望这有意义,还是我想把它分成2个perl脚本?感谢您的投入。

代码(WIP):

open FILE, "< /home/myname/FileList.txt";
while (<FILE>) {
 my $line = $_;
   chomp($line);
      print "Content:$_"; #This is just printing the filenames. 
                #I want to get the contents of those file names instead. Stuck here.
      if ($line =~ m/home\/myname\/(\w{3}).*[.](\w+)[.].*/){
         print "Key1:$2:Key2:$1\n";
      }
}
close FILE;

FileList.txt的内容:

/home/myname/col/.my_file_del.mail@locale.foo.org
/home/myname/col/.my_file_del.dp1.bar.net
/home/myname/jab/.my_file_del.mail@locale.foo.org
/home/myname/jab/.my_file_del.dp1.bar.net

列出的文件之一的示例内容:(我需要帮助以提取)

$ cat .my_file_del.mail@locale.foo.org 
locale_col.dat.2010120813.png

预期产出:

Content:locale_col.dat.2010120813.png
Key1:foo:Key2:col
...
..

2 个答案:

答案 0 :(得分:3)

如果您有文件名,为什么不打开它们?

use strict;
use warnings;
use 5.010;
use autodie;

open my $fh, '<', '/home/myname/FileList.txt';
while (my $line = <$fh>) {
    chomp $line;
    say "Key1:$2:Key2:$1" if m!home/myname/(\w{3})[^.]*[.](\w+)[.].*!;
    next unless -e $line; #We skip to the next line unless the file exists
    open my $inner_fh, '<', $file;
    while (<$inner_fh>) {
        say;
    }
}

答案 1 :(得分:3)

这是一种方法:

#!/usr/bin/perl
# ALWAYS these 2 lines !!!
use strict;
use warnings;

my $file = '/home/myname/FileList.txt';
# use 3 args open and test openning for failure
open my $FILE, '<', $file or die "unable to open '$file' for reading: $!";
while (my $line = <$FILE>) {
    chomp($line);
    print "Content:$line\n"; #This is just printing the filenames. 
    #I want to get the contents of those file names instead. Stuck here.
    if ($line =~ m#home/myname/(\w{3}).*[.](\w+)[.].*#) {
        open my $file2, '<', $line or die "unable to open '$file' for reading: $!";
        while(my line2 = <$file2>) {
          print $line2;
        }
        close $file2;
        print "Key1:$2:Key2:$1\n";
    }
}
close $FILE;