linux&Perl&R  

perl中seek函数的用法——改变文件指针

seek 设置文件的当前位置!

当一个文件非常大时可以从指定位置读起。
seek FILEHANDLE,POSITION,WHENCE   

成功返回真,失败返回假。
POSITION 是读入的新位置(字节)。
WHENCE有3个值,0表示新位置是POSITION,1表示当前位置加上POSITION,2表示文件尾加上POSITION
例如:从file.txt的12字节开始读起并打印出来。
open (FILEHANDLE,"<file.txt") or die "cannot open file.txt";
seek FILEHANDLE,12,0;
while (<FILEHANDLE>){
        print;
}
close (FILEHANDLE);

 

例子:

 

Read Line And Selected Subsequent Lines

#!/usr/bin/perl


open (TEST, "<E:/test.txt");
while (<TEST>) {
   if (index ($_, "keyword") > -1) {
    $position = tell(TEST);
    $keyword_line = $_;
    $line_1 = <TEST>;
    $line_2 = <TEST>;
    $line_3 = <TEST>;
    print " $keyword_line $line_1 $line_2 $line_3\n\n";
    if (!($line_1)) { print " __End Of File__"; last; }
    if (!($line_2)) { print " __End Of File__"; last; }
    if (!($line_3)) { print " __End Of File__"; last; }
    seek(TEST, $position, 0);
   }
}

close (TEST);
exit;

test.txt:

skip this line
A keyword is here
print this line
Trick location of keyword
print this line
print this line
print this line
skip this line
skip this line
This is another keyword
print this line
print this line
print this line
skip this line
Last line and a keyword

 

 

PRINTED RESULTS:

A keyword is here
 print this line
 Trick location of keyword
 print this line


 Trick location of keyword
 print this line
 print this line
 print this line


 This is another keyword
 print this line
 print this line
 print this line


 Last line and a keyword
 
 

 __End Of File__


2012-07-19

评论

©linux&Perl&R Powered by LOFTER