【问题标题】:How to search multiline txt files between two known lines in perl如何在perl中的两个已知行之间搜索多行txt文件
【发布时间】:2013-12-17 20:17:45
【问题描述】:

我是 perl 新手,正在尝试用 perl tk 编写程序。我有大部分,但似乎无法得到最后一点。

我正在阅读一个看起来像这样的 .txt 文件...

display ("Blue")
....
....
....
....
display ("Yellow")
....
bobby
....
....
display ("Red")
....
.... and so on

“....”是我并不真正关心的数据部分,但我必须搜索才能找到“bobby”。

我已经建立了一个数组来存储所有带有显示的行。即@array。我想在原始 .txt 文件中包含“显示”的每一行之间搜索“鲍比”,并输出其上方的任何显示行。

对于上面的例子,我想要一个

的输出

显示(“黄色”)

我认为我需要一个 while 循环来在我想要搜索的显示之间的所有区域之间进行迭代。

下面的代码显示了我构建的一些内容。 输入完成后按下按钮时,将运行以下子程序。

#Output Substation ID to Pane
sub find_substations 
{
       #Copy the entry
my $substation_to_search = $find_ensub->get();

#Insert the copied entry into the outptutext_box
$output_textbox->insert("end", "Substation ID: $substation_to_search\n\n");

       open(myfile1, "file and file location");
       my @lines = <myfile1>;
       #Open File and Print all lines with display in it.
       my @array= grep(/display /,@lines);
       #Array Size
       my $size = @array;
       my $start = $lines[0];
       my $stop = $lines[1];

    while("$x" < "$size")
    {       
     if("$start".."$stop")
     {  
      next if /$start/||/$stop/;
      if()          
      {
        $output_textbox->insert("end", "$lines[0]");
      }#if stop
      }#If stop

     $x++;
     }
   #close myfile1;

}

我一直在阅读有关启动和停止的信息,但无法使其正常工作。谁能帮我吗?启停部分的代码不完整。

【问题讨论】:

  • 对于初学者,不要不必要地在变量周围加上引号。当您尝试将它们视为数字时,这也可能会咬您:"$x" &lt; "$size"

标签: windows perl


【解决方案1】:

如果我正确理解你的问题,我认为你把问题复杂化了。无需跟踪边界(您的$start 和$end),只需跟踪display 的当前值。例如:

文件:

display ("Blue")
foo
bar
display ("Yellow")
baz
bobby
qux
display ("Red")
pop
bobby

script.pl:

 #!/usr/bin/perl
 use strict;
 use warnings;

 open(my $fh, '<', "./".$ARGV[0]) or die("Cannot open file");

 my $display;
 while (<$fh>) {
   $display = $_ if /^display/;
   print $display if /^bobby$/;
 }

产量:

$ perl ./script.pl ./infile
display ("Yellow")
display ("Red")

【讨论】:

  • 谢谢!我不确定是否有命令可以执行您上面所做的操作。完美的。通过一些修改它可以完美地工作。
猜你喜欢
  • 2011-03-09
  • 2016-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-07
相关资源
最近更新 更多