【问题标题】:perl split file based on file stringperl 根据文件字符串拆分文件
【发布时间】:2014-10-21 20:12:36
【问题描述】:

我正在尝试将一个非常大的文件拆分为文件中基于字符串的较小文件。

例如。输入文件

 Block(A){
   Block_area : 2.6112;
   Block_footprint : 3BAA5927A22E66B0AE1214A806440F12;
 }
 Block(B){
   Block_area : 2.6112;
   Block_footprint : 3BAA5927A22E66B0AE1214A806440F12;
 }
 Block(C){
   Block_area : 2.6112;
   Block_footprint : 3BAA5927A22E66B0AE1214A806440F12;
 }

我想创建三个文件,每个文件都包含括号内的数据

请告诉我我哪里弄错了。我的 perl 代码

while (<PR>) {
    if ($_ =~ ' Block\('))
    {
        chomp;
    close (PW);
        $textcell = $_;
        $textcell =~ s/Block\(//g;
        $textcell =~ s/\)\{//g;
    open (PW, ">$textcell.txt") or die "check file";
    }
    if ( /^  Block\($textcell\)/../^  }/)
    { print PW  $_;}
}

正在创建所需的文件,但为空。

问候


想要的输出,三个文件:

A.txt

 Block(A){
   Block_area : 2.6112;
   Block_footprint : 3BAA5927A22E66B0AE1214A806440F12;
 }

B.txt

 Block(B){
   Block_area : 2.6112;
   Block_footprint : 3BAA5927A22E66B0AE1214A806440F12;
 }

C.txt

 Block(C){
   Block_area : 2.6112;
   Block_footprint : 3BAA5927A22E66B0AE1214A806440F12;
 }

【问题讨论】:

  • 请也添加您想要的输出示例。
  • Block(之前有多少个空格?

标签: perl


【解决方案1】:

问题是您的测试排除了不是Block() 行的任何内容。对于任何其他形式的生产线,您什么都不做。此外,您的第二条if 语句正在检查Block 之前是否有两个 空格,这永远不会发生。

我就是这样写的。它假定至少是 Perl 5 的第 10 版,这样我就可以使用 autodie 而不是显式检查每个 open 调用的成功与否。请注意,我在正则表达式中使用了 /x 修饰符,因此空格和制表符无关紧要,我可以使用它们使正则表达式更具可读性。

use strict;
use warnings;
use 5.010;
use autodie;

open my $in_fh, '<', 'blocks.txt';

my $out_fh;

while (<$in_fh>) {
  open $out_fh, '>', "$1.txt" if / Block \( (\w+) \) /x;
  print $out_fh $_ if $out_fh;
}

【讨论】:

    【解决方案2】:

    我建议改变方法并以块而不是行来读取文件,

    use strict;
    use warnings;
    use 5.010;
    use autodie;
    
    # input record separator is now '}' followed by old value of separator (i.e \n)
    local $/ = "}$/";
    
    while (<>) {
      my ($file) = m|\( (.+?) \)|x or next;
    
      open my $fh, ">", "$file.txt";
      print $fh $_;
      close $fh;
    }
    

    【讨论】:

    • 我发现use 5.010use autodie 之前很有用。这样,Perl 就会抱怨它的版本不足,而不是关于找不到 autodie 的不太有用的消息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-30
    • 1970-01-01
    • 1970-01-01
    • 2013-06-06
    • 2015-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多