bash:替换文本块

bash:替换文本块,bash,sed,Bash,Sed,我有一份档案 # my file # is here section1 { foo nothing important } section2 { this is important this is also important } 我需要用其他内容替换第一节的内容: section1 { bar really important } 我尝试过使用sedregex匹配,但它捕捉到了第二节结尾的括号。我怎么做?欢迎使用除s

我有一份档案

# my file
# is here

section1 {
      foo
      nothing important
}
section2 {
      this is important
      this is also important
}
我需要用其他内容替换第一节的内容:

section1 {
      bar
      really important
}
我尝试过使用
sed
regex匹配,但它捕捉到了第二节结尾的括号。我怎么做?欢迎使用除sed以外的其他工具


谢谢

这里有一个快速而肮脏的perl文件可以做到这一点:

#!/usr/bin/perl

open ( INFILE, 'document.txt' ) || die "Cannot read input file.";
open ( OUTFILE, '>document2.txt' ) || die "Cannot write output file.";

$replaced = "0";

while ( $line_in = <INFILE> ) {
    print OUTFILE $line_in;
    next unless $line_in =~ /^\s*section1 {\s*$/ && $replaced eq "0";
        print OUTFILE "      bar\n";
        print OUTFILE "      really important\n";
        while ( $line_in = <INFILE> ) {
            next unless $line_in =~ /^\s*}\s*$/;
                print OUTFILE $line_in;
                $replaced = "1";
                last;
        }
}

close ( INFILE );
close ( OUTFILE );
#/usr/bin/perl
打开(infle,'document.txt')| | die“无法读取输入文件。”;
打开(OUTFILE,'>document2.txt')| | die“无法写入输出文件。”;
$replaced=“0”;
while($line_in=){
打印输出文件$line_in;
下一步,除非=~/^\s*节1{\s*$/&&$中的$line_替换了等式“0”;
打印输出文件“bar\n”;
打印输出文件“非常重要\n”;
while($line_in=){
下一步除非$line_in=~/^\s*}\s*$/;
打印输出文件$line_in;
$replaced=“1”;
最后;
}
}
关闭(填充);
关闭(输出文件);

它确实保留了原始文件,并为您提供了第二个进行编辑的文件,而不是在适当的位置编辑原始文件,但它更像是一个让您开始的基本原则的示例。

您可以共享您的正则表达式吗?
{echo“New section 1”;grep-A999“section 2”originalFile;}>newFile
可能?