簡體   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