【问题标题】:How do I use sed to replace all lines between two matching patterns (on OSX BSD)如何使用 sed 替换两个匹配模式之间的所有行(在 OSX BSD 上)
【发布时间】:2014-01-25 15:50:29
【问题描述】:

我想知道如何:

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

  • 替换两个匹配模式(包括)之间的所有行。请注意,这些将在不同的行上 我已经开始了第一个,但它没有产生预期的结果(到目前为止还没有结果)。请记住,这适用于 Mac OSX (BSD) 上的 sed。本例中的模式是 两个 html cmets 在不同的行上。

我的 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>

【问题讨论】:

  • 您是绑定到 sed 还是允许使用其他工具(例如 awk)?
  • 我不介意看到 awk 解决方案,目前我最熟悉 sed。我也想忠于标题。
  • 您希望文件在 操作后看起来像什么?
  • 我将在上面添加以显示示例文件 a ab

标签: regex macos shell sed bsd


【解决方案1】:

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"; 
'

【讨论】:

    【解决方案2】:
    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 逐行工作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-04
      • 1970-01-01
      • 2013-02-27
      相关资源
      最近更新 更多