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 

谢谢

4

2 回答 2

2

你试过什么了?

这是一个简短的程序,可以为您提供问题的核心,您可以添加其余部分:

尽管( )
    {
    s|http://.*/\d+/(\d+)/(\d+).*?jpg|php?id=$1$2|;
    打印;
    }

这非常接近命令行程序,它使用-p开关为您处理循环和打印(有关详细信息,请参阅perlrun文档):

perl -pi.old -e 's|http://.*/\d+/(\d+)/(\d+).*?jpg|php?id=$1$2|' inputfile > outputfile
于 2008-12-12T07:40:01.177 回答
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();
于 2008-12-12T07:44:56.987 回答