Perl - 在文件中找到匹配项后插入的行

时间:2010-08-06 08:53:45

标签: perl

我在some_1.xyz

中有一个具有以下语法的文件
module some_1 {
INPUT PINS
OUTPUT PINS
}

我想在行模块some_1 {

之后插入APPLY DELAYS xx和APPLY LOADS ld

以下代码仅适用于一个文件,即,如果我将some_1.xyz替换为* .xyz,则脚本不起作用。我尝试引入sleep(xx),但代码不适用于多个文件,我无法弄清楚它为什么不起作用。任何指针都表示赞赏。感谢

@modulename_array = `grep "module " some_1.xyz | cut -f 2 -d ' '`;
@line = `grep "module " some_1.xyz`;

chomp(@line);
chomp(@kfarray);

$i = 0;
foreach (@modulename_array) {
  print "Applying delay and load to $_.xyz $line[$i] \n";

  `perl -ni -le 'print; print "\tAPPLY DELAY xx \n \tAPPLY LOADS  ld\n" if/$line[$i]/' $_.xyz`;
  $i++;
  #sleep(3);

}

5 个答案:

答案 0 :(得分:4)

更简单一些,只使用SED一行(如果此问题仅适用于UNIX,且匹配是固定值,而不是正则表达式):

sed -i -e "s/<match pattern>/<match pattern>\n<new line here>/g" file.txt

(与初始响应相比,选项已被交换,因为第一条评论。)

注意\ n是添加新行。此致

答案 1 :(得分:3)

这个简单的解决方案有什么问题?:

$data=`cat /the/input/file`;
$data=~s/some_1 {\n/some_1 {\nAPPLY DELAYS xx\nAPPLY LOADS ld\n/gm;
print $data;

答案 2 :(得分:0)

我不知道为什么你的代码不能正常工作,但是我在Perl里面使用Perl里面的反引号时遇到了麻烦。这是未经测试的,但应该有效。我建议你也“严格使用”;和“使用警告;”。

my @files = ("some_1.xyz", "some_2.xyz", ... );
for my $file in ( @files )
{
    my $outfile = $file + ".tmp";
    open( my $ins, "<", $file ) or die("can't open " . $file . " for reading: " . $!);
    open( my $outs, ">", $outfile ) 
        or die("can't open " . $outfile . " for writing: " . $!);
    while ( my $line = <$ins> )
    {
        print { $outs } $line;
        if ( $line =~ m/^module\s+/ )
        {
             print { $outs } "\tAPPLY DELAY xx\n\tAPPLY LOADS ld\n";
        }
    }
    rename( $outfile, $file );
}

答案 3 :(得分:0)

$text='bla bla mytext bla bla';
$find='.*mytext.*';
$repl='replacement';

$text=~ s/($find)/$1$repl/g;

$ 1基本上是您的匹配项,您可以在进行替换时在$ repl字符串之前或之后使用它。 )))

容易

答案 4 :(得分:0)

单线

perl -pi -e '/module some_1/ and $_.="APPLY DELAY xx \nAPPLY LOADS  ld\n"' files*.txt
相关问题