+ -
当前位置:首页 → 问答吧 → 如何用perl 从文件里面抓一段内容出来?

如何用perl 从文件里面抓一段内容出来?

时间:2011-05-06

来源:互联网

假设文件 output.txt的内容如下:
====================
the following are the list of products:
airplan
jet
bullet
gun
the following are the list of money:
RMB
Dollar
Riyuan
====================

现在我想把两个list的title和内容,分别放到两个不同的文件中去,比如:
the following are the list of products:
shoe
table
bug
放到文件 product.txt里面去。同样的,另外一个放到 money.txt里面去。但我只知道用//可以查找,但接下怎么把这块内容截出来,我就不会了。向大侠们请教。

open FILE, "< output.txt";

while(<FILE>)
{
     if (/the following are the list of products:/)
    {
    }

    if (/the following are the list of money:/)
    {

    }
}

作者: 百分百好牛   发布时间: 2011-05-06

  1. open FILE, "< output.txt";
  2. open OUT, ">> out.txt" or die "fail:$!";
  3. while(<FILE>)
  4. {
  5.      if (/the following are the list of products:/)
  6.     {
  7.         print OUT "$_";
  8.     }

  9.     if (/the following are the list of money:/)
  10.     {

  11.     }
  12. }
复制代码

作者: lkk2003rty   发布时间: 2011-05-06

谢谢楼上的兄弟先,你的这个方法,只能把 title 如"the following are the list of products:" 打印到文件吧,后面紧跟着的list呢?

谢谢。

作者: 百分百好牛   发布时间: 2011-05-06

回复 百分百好牛


    用个变量标示 控制下 就是了
    my $flag;
     if(/regex/)
     {
        $flag=1;
      }
      print OUT "$_" if $flaf == 1;
类似这样  不同的段 flag设成不同的值就是了

作者: lkk2003rty   发布时间: 2011-05-06

let me try it, thx.

作者: 百分百好牛   发布时间: 2011-05-06



QUOTE:
假设文件 output.txt的内容如下:
====================
the following are the list of products:
air ...
百分百好牛 发表于 2011-05-06 10:05




$ cat output.pl
  1. use strict;
  2. use warnings;

  3. my $sOut_file="";
  4. open(FILE, "<", "output.txt") or die "can't open output.txt\n";

  5. while(<FILE>){
  6.     # the following are the list of products:
  7.     # the following are the list of money:
  8.     if (/the following are the list of (.+):/){
  9.         close(FHout) if($sOut_file ne "");
  10.         $sOut_file = "$1.txt";
  11.         open(FHout, ">", $sOut_file) or die "can' open $sOut_file\n";
  12.         print "open $sOut_file file to write data\n";
  13.      }
  14.      print FHout $_;
  15. }
  16. close FHout;
复制代码
$ perl output.pl
open products.txt file to write data
open money.txt file to write data
$

作者: jason680   发布时间: 2011-05-06