【问题标题】:sed: replace a block of textsed:替换文本块
【发布时间】:2012-10-14 04:26:38
【问题描述】:

我有一堆文件,从一段代码开始,我正在尝试用另一个替换。

替换:

<?php
$r = session_start();
(more lines)

与:

<?php
header("Location: index.php");
(more lines of code)

所以我试图将块与sed 's/&lt;?php\n$r = session_start();/&lt;?php\nheader... 匹配,但它不起作用。

对于这里发生的事情以及如何实现这一点,我将不胜感激。我正在考虑用 python 来代替。

谢谢!

【问题讨论】:

  • 您可以添加任何额外的信息吗?从外观上看,您只想更改每个文件中的第二行。对吗?
  • 超过第二行,是一段代码,我想替换的旧代码(每个文件开头大约4或6行)
  • 这对我不起作用。我正在尝试将文本块替换为其他文本,并且无法使用您提供的这个 sed 示例来完成。这就是我想做的,匹配文本块并将其替换为另一个。在此示例中,我想替换以下文本块:“第 2 行原始文本第 1 行第 2 行第 3 行

标签: bash unix replace sed awk


【解决方案1】:

这可能对你有用(GNU sed):

sed -i '1i\
This is a\
new block of\
code
1,/$r = session_start();/d' file 

或者,如果您希望将新代码放在文件中:

sed -i '1r replacement_code_file
1,/$r = session_start();/d' file

全部在一条线上:

sed -i -e '1r replacement_code_file' -e '1,/$r = session_start();/d' file

【讨论】:

    【解决方案2】:

    一种使用sed的方式:

    cat block.txt <(sed '1,/$r = session_start();/d' file.txt) > newfile.txt
    

    只需将要添加到每个文件的文本块添加到block.txtsed 组件只是删除第一行和匹配模式之间的行。

    【讨论】:

      【解决方案3】:

      sed,稍微调整一下您的解决方案:

      sed  '/<?php/{N;s/\n$r = session_start();/\nheader(\"Location: index.php\");/}' file
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-19
        • 1970-01-01
        • 2014-12-22
        • 2011-11-25
        • 2022-10-21
        • 2010-11-24
        • 2010-10-27
        相关资源
        最近更新 更多