2008-12-12 129 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(); 
相關問題