2008-12-12 130 views
1

我想让Perl脚本从文本文件中提取数据并将其另存为另一个文本文件。文本文件的每一行都包含一个指向jpg的URL,如“http://pics1.riyaj.com/thumbs/000/082/104//small.jpg”。我希望脚本将每个jpg URL的最后6个数字(即082104)提取到一个变量中。我希望将变量添加到新文本每一行的不同位置。如何从文本文件中提取数字数据?

输入文本:

text http://pics1.riyaj.com/thumbs/000/082/104/small.jpg text 
text http://pics1.riyaj.com/thumbs/000/569/315/small.jpg text 

输出文本:

text php?id=82104 text 
text php?id=569315 text 

感谢

+0

是他们你有自己写的任何具体问题?另外,URL是否总是您描述的形式,或者您是否需要能够处理任意URL? – mweerden 2008-12-12 07:37:54

回答

2

你尝试过这么远吗?

这里有一个小程序,让你的问题的肉,你可以添加它的其余部分:

 
while() 
    { 
    s|http://.*/\d+/(\d+)/(\d+).*?jpg|php?id=$1$2|; 
    print; 
    } 

这是非常接近的命令行程序手柄的循环和印刷的你与-p开关(见细节perlrun文档):

perl -pi.old -e 's|http://.*/\d+/(\d+)/(\d+).*?jpg|php?id=$1$2|' inputfile > outputfile 
1

我不知道是否要根据你所描述的(“最后6个位数”),或者只是回答假设它适合所有的你展示的模式。所以我决定回答这两个方面。

这是一种可以处理比您的示例更多样化的线条的方法。

use FileHandle; 

my $jpeg_RE = qr{ 
    (.*?)   # Anything, watching out for patterns ahead 
    \s+    # At least one space 
    (?> http://) # Once we match "http://" we're onto the next section 
    \S*?   # Any non-space, watching out for what follows 
    ((?: \d+ /)* # At least one digit, followed by a slash, any number of times 
     \d+   # another group of digits 
    )    # end group 
    \D*?   # Any number of non-digits looking ahead 
    \.jpg   # literal string '.jpg' 
    \s+    # At least one space 
    (.*)    # The rest of the line 
}x; 

my $infile = FileHandle->new("<$file_in"); 
my $outfile = FileHandle->new(">$file_out"); 

while (my $line = <$infile>) { 
    my ($pre_text, $digits, $post_text) = ($line =~ m/$jpeg_RE/); 
    $digits  =~ s/\D//g; 
    $outfile->printf("$pre_text php?id=%s $post_text\n", substr($digits, -6)); 
} 
$infile->close(); 

但是,如果你表现出它只是作为常规,它变得轻松了许多:

use FileHandle; 
my $jpeg_RE = qr{ 
    (?> \Qhttp://pics1.riyaj.com/thumbs/\E) 
    \d{3} 
    /
    (\d{3}) 
    /
    (\d{3}) 
    \S*? 
    \.jpg 
}x; 

my $infile = FileHandle->new("<$file_in"); 
my $outfile = FileHandle->new(">$file_out"); 

while (my $line = <$infile>) { 
    $line =~ s/$jpeg_RE/php?id=$1$2/g; 
    $outfile->print($line); 
} 
$infile->close();