简体   繁体   English

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

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

I would like to know how to: 我想知道如何:

  • Replace all lines between two matching patterns (not include the patterns - exclusive). 替换两个匹配模式之间的所有行(不包括模式-排他)。 Please note that these will be on separate lines. 请注意,这些将在单独的行上。

  • Replace all lines between and including two matching patterns (inclusive). 替换介于两个匹配模式(包括两个)之间的所有行。 Please note that these will be on separate lines I have started the first, but its not producing the desired results (actaully no results so far). 请注意,这些将在我已经开始的单独的一行上,但是没有产生预期的结果(到目前为止,实际上没有任何结果)。 Please keep in mind that this is for sed on Mac OSX (BSD) . 请记住,这是中美战略经济对话Mac OSX(BSD)。 The pattern in this case is two html comments on separate lines. 在这种情况下,模式是在单独的行上包含两个html注释

My shell script looks like this: 我的shell脚本如下所示:

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

In the head of my index.php file is this excerpt: 在我的index.php文件的开头是以下摘录:

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

example result a 示例结果a

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

    </body>
</html>

example result b 示例结果b

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

    </body>
</html>

A perl one-liner: Perl单线:

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

This uses the -0777 option to read the entire file as a single string, which requires the s modifier on the s///s command 它使用-0777选项读取整个文件作为一个字符串,这就需要s上的修饰s///s命令

That one-liner is roughly equivalent to 一线大致相当于

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

You need to load the file into the buffer becasue sed work line by line 您需要将文件加载到缓冲区中,因为sed逐行工作

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

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