如何在一行中添加特定字符串

时间:2014-03-25 13:52:41

标签: string perl

我有以下遗留代码:

  open(FILE_Errors,">Errors.txt") || die "Error at >";     
  undef(@arrayrow);                  

  open(File_To_Read,"<$file") || die "File not Found";
  while($row=<File_To_Read>) {
    push(@arrayrow,$row);
  }
  close(File_To_Read);

  foreach(@arrayrow) {
    if($_=~ m/errorcode: 230/i) {       
        print FILE_Errors "$_";
    } elsif($_=~ m/errors/i) {
        print FILE_Errors "$_";
    }
  }
}
close (file);

此代码加载文件并搜索包含errorcode: 230errors的行 - 这样可以正常工作。它将找到的行打印到Errors.txt中 - 这也很完美。

这会改变:

文件A.txt:

lorem ipsum errorcode: 230
loem ipsum

文件B.txt:

lorem ipsum
loem errors ipsum

ERRORS.TXT:     lorem ipsum错误代码:230     错误的错误ipsum

现在它应该从哪个文件追加这些行。 ERRORS.TXT:

lorem ipsum errorcode: 230 A.txt
loem errors ipsum B.txt

我尝试了什么以及相关的输出(对我来说没有意义): 行等于lorem ipsum errorcode ..

print FILE_Errors "$file $_" # produces:
A.txt line
 A.txt line
 A.txt line
 B.txt line
 B.txt line

print FILE_Errors "$_ $file" # produces:
line
 A.txtline
 A.txtline
 A.txtline
 B.txtline
 B.txt

我如何安排变量来获取:

line A.txt
line B.txt

PS:我已经阅读了Perl for Java introduction

edit1:@Jonathan Leffler

chomp;
print FILE_Errors "$_ $file\n";
#will produce:
A.txt line
A.txt line
A.txt line
B.txt line
B.txt line

通过将语句更改为:&#34; $ file $ _ \ n&#34;它会工作。谢谢!

2 个答案:

答案 0 :(得分:2)

使用chomp删除尾随换行符,然后在打印中添加文件名和换行符:

chomp;
print FILE_Errors "$_ $file\n";

请注意,在您的脚本中,close(file);并未关闭任何已打开的文件(但该行和它在脚本提取中的闯入者之前的大括号;问题并非如此; t显示平衡开放式支架)。此外,除非阵列上的处理数量多于显示的数量,否则无需将整个文件粘贴到内存中;你可以一次处理一行。如果您确实需要一次内存中的所有数据,则可以将整个while循环缩减为:

@arrayrow = <File_to_Read>;

答案 1 :(得分:1)

您的脚本可以在很大程度上被Perl内置功能取代,并且可以简单地完成:

perl -nlwe'/error(?:s|code: 230)/i and print' input1 input2 ... > errors.txt

您也可以将其放在源文件中:

use strict;
use warnings;

while (<>) {
    /error(?:s|code: 230)/i and print;
}

如果需要,您可以对路径进行硬编码,或使其成为可选路径:

my $error_output = shift || "errors.txt";
open my $outfh, ">", $error_output or die "Cannot open $error_output: $!";

虽然就个人而言,我宁愿键入自己的路径,因为它不太可能让你感到惊讶。

请注意,正则表达式是两个正则表达式的组合版本。另请注意,您应该使用显式模式open的三个参数">",词法文件句柄(而不是全局)和显式错误检查,使用$!错误显示出错的地方