+ -
当前位置:首页 → 问答吧 → perl可以实现这样的匹配吗

perl可以实现这样的匹配吗

时间:2010-11-15

来源:互联网

文件包括:
.....
monday.........
tuesday........
wednsday........
thursday........
friday..........
saturday......
....

perl如何实现:匹配从包含friday的行开始到文件最后或者到指定字符串,将中间的这些内容输出到一个新文件中。

我有个方法,但不是很好:
main.pl中
调用system("test.sh")
然后在test.sh中,用sed -n '/friday/,$p' file > file2
这样是可以实现的,但较为啰嗦,需要用两个程序执行:main.pl和test.sh

当我在main.pl中,
直接用system("/usr/bin/sed -n '/friday/,$p' file > file2");
程序出错,提示:sed: command garbled:

如果用sed,可以在一个程序里写完吗?若是不用sed,perl有没有直接的匹配方法呢?

作者: zljjg2000   发布时间: 2010-11-15

本帖最后由 jason680 于 2010-11-15 17:41 编辑

回复 zljjg2000

while(<>){
  $out = 1 if (m/friday/);
  print if $out;
}


or

perl -lane '{$out = 1 if (m/friday/); print if $out;}' file1 > file2

作者: jason680   发布时间: 2010-11-15

回复 jason680


    这个很强大 能不能讲解下?为什么这样写就能到文件末尾呢?

作者: jiannma   发布时间: 2010-11-15

  1. #!/bin/env perl

  2. use strict;
  3. use warnings;

  4. # using DATA
  5. my $pos = tell(DATA);
  6. while (<DATA>)
  7. {
  8.         if (/friday/ .. eof(DATA))
  9.         {
  10.                 print;
  11.         }
  12. }

  13. print "====================\n";

  14. seek(DATA, $pos, 0);
  15. while (<DATA>)
  16. {
  17.         if (/friday/ .. /saturday/)
  18.         {
  19.                 print;
  20.         }
  21. }

  22. __DATA__
  23. monday.........
  24. tuesday........
  25. wednsday........
  26. thursday........
  27. friday..........
  28. saturday......
  29. ...
复制代码

作者: 黑色阳光_cu   发布时间: 2010-11-15