【问题标题】:How to read a file which is gzipped and tar in perl如何读取在 perl 中压缩和 tar 的文件
【发布时间】:2014-06-20 10:33:17
【问题描述】:

我已将文本文件“FilenameKeyword.txt”文件放在 E:/Test 文件夹中,在我的 perl 脚本中,我试图遍历该文件夹,并且我试图找到一个文件名具有字符串“关键字”,稍后我在脚本中打印了该文件的内容。 现在我希望对放置在压缩的 tar 文件中的文件做同样的事情。

我试图从中提取详细信息的假设文件: E:\test.tar.gz

想知道perl是否有可能在不解压/解压缩假设文件的情况下搜索和读取文件。如果不可能,我还将分配一些临时内存来解压文件,解压后应该删除来自特定文本文件的内容。

在互联网上搜索时,我可以使用 Archive::Extract 来提取和读取 gzip/tar 文件,这是 Perl 的新手——我真的很困惑我应该如何使用它。你能帮忙解决这个问题吗....

输入文件:FilenameKeyword.txt

脚本:

use warnings;
use strict;

my @dirs = ("E:\\Test\\");
my %seen;
while (my $pwd = shift @dirs) {
        opendir(DIR,"$pwd") or die "Cannot open $pwd\n";
        my @files = readdir(DIR);
        closedir(DIR);
        foreach my $file (@files) 
        {
                if (-d $file and ($file !~ /^\.\.?$/) and !$seen{$file}) 
                {
                        $seen{$file} = 1;
                        push @dirs, "$pwd/$file";
                }
                next if ($file !~ /Keyword/i);
                my $mtime = (stat("$pwd/$file"))[9];
                print "$pwd$file";
                print "\n";
                open (MYFILE, "$pwd$file");
                while (my $line = <MYFILE>){
                #print $line;
                my ($date) = split(/,/,$line,2);
                if ($line =~ s!<messageText>(.+?)</messageText>!!is){
                print "$1";
                }
                }

        }
}

输出(在测试程序文件放在E:\Test下):

E:\Test\FilenameKeyword.txt
1311 messages Picked from the Queue.

寻求帮助以检索位于下的文件的内容 E:\test.tar.gz

期望的输出:

E:\test.tar.gz\FilenameKeyword.txt
1311 messages Picked from the Queue. 

【问题讨论】:

标签: perl perl-module


【解决方案1】:

如果您的文件仅经过 gzip 压缩,您可以按照here (Piping to/from a child process without system or backtick - gzipped tar files) 所述的“流式传输”方式读取其内容。本文说明了一种使用 open 和 fork 来打开和解压缩文件的技术,然后将其提供给 Perl 的 while(),从而允许您对其进行迭代。

由于 tar 基本上是连接事物,因此可以根据您的场景进行调整。

【讨论】:

    【解决方案2】:

    我一直在使用 CPAN 模块,CPAN 模块对我不起作用,因为我在同一台机器上安装了 oracle 10g 企业版,由于某些软件冲突活动状态 perl 无法编译并参考 CPAN 的 perl 库模块,我已经在我的机器上卸载了 oracle 来完成这项工作....

    #!/usr/local/bin/perl
    use Archive::Tar;
    my $tar = Archive::Tar->new;
    $tar->read("test.tar.gz");
    $tar->extract();
    

    【讨论】:

    • 虽然措辞不佳,但这实际上似乎是在提出解决方案。它也是迄今为止唯一尝试过的解决方案,因此删除它根本不会留下任何答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-24
    • 1970-01-01
    • 2016-08-02
    • 1970-01-01
    • 2010-10-13
    • 2012-09-29
    • 1970-01-01
    相关资源
    最近更新 更多