繁体   English   中英

如何使用sed替换两个匹配模式之间的所有行(在OSX BSD上)

[英]How do I use sed to replace all lines between two matching patterns (on OSX BSD)

我想知道如何:

  • 替换两个匹配模式之间的所有行(不包括模式-排他)。 请注意,这些将在单独的行上。

  • 替换介于两个匹配模式(包括两个)之间的所有行。 请注意,这些将在我已经开始的单独的一行上,但是没有产生预期的结果(到目前为止,实际上没有任何结果)。 请记住,这是中美战略经济对话Mac OSX(BSD)。 在这种情况下,模式是在单独的行上包含两个html注释

我的shell脚本如下所示:

REPLACEWITH="Replacement text here"
sed -i '' -e "s&\(<!--BeginNotes-->\).*\(<!--EndNotes-->\)&\1$REPLACEWITH\2&" /Users/BlaNameHere/builds/development/index.php

在我的index.php文件的开头是以下摘录:

<!--BeginNotes-->
    <!--asdasd-->
    <script type="application/javascript">var Jaop;</script>
<!--EndNotes-->

示例结果a

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <!--BeginNotes-->
        Replacement text here
        <!--EndNotes-->
    </head>
    <body>

    </body>
</html>

示例结果b

<!DOCTYPE html>
<html>
    <head>
        <title></title>
Replacement text here
    </head>
    <body>

    </body>
</html>

Perl单线:

perl -i -0777 -pe 's/(<!--BeginNotes-->).*(<!--EndNotes-->)/$1'"$REPLACEWITH"'$2/s' index.php

它使用-0777选项读取整个文件作为一个字符串,这就需要s上的修饰s///s命令

一线大致相当于

perl -e '
    # read the file as a single string
    open $in, "<", "index.php";
    my $text;
    {
        local $/; 
        $text = <$in>;
    }
    close $in;

    # transform the string
    $text =~ s/(<!--BeginNotes-->).*(<!--EndNotes-->)/$1'"${REPLACEWITH}"'$2/s;

    # write out the new string
    open $out, ">", "index.php.tmp";
    print $out $text;
    close $out;

    # over-write the original file
    rename "index.php.tmp", "index.php"; 
'
sed -n ":b
$ !{
   N
   b b
   }
$ {
   s|\(<!--BeginNotes-->\).*\(\n\)\([[:blank:]]*\)\(<!--EndNotes-->\)|\1\2\3${REPLACEWITH}\2\3\4|
   p
   }" /Users/BlaNameHere/builds/development/index.php

您需要将文件加载到缓冲区中,因为sed逐行工作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM