regex - 我如何在 sed 的正则表达式中包含换行搜索

标签 regex linux sed

基本上我有一个文本文件,我想在其中替换多行的行

我正在使用这个代码

sed -rn ':a;N;$!ba;s/if(.*):://gp' file.txt

基本上,我将所有行都放入内存中,然后搜索模式。

我希望 (.*) 也匹配新行,但它没有这样做。我做错了什么

编辑

这是文件

<?php

if (!isset($_SERVER['HTTP_HOST'])) {
    exit('This script cannot be run from the CLI. Run it from a browser.');
}

if (!in_array(@$_SERVER['REMOTE_ADDR'], array(
    '127.0.0.1',
    '::1',
))) {
    header('HTTP/1.0 403 Forbidden');
    exit('This script is only accessible from localhost:: .');
}

require_once dirname(__FILE__).'/../app/SymfonyRequirements.php';

我想删除 require_once 和 if(!in_array) 之前的内容

reuire_once 不应该用作匹配项,因为它在其他文件中可能不同

输出

<?php

if (!isset($_SERVER['HTTP_HOST'])) {
    exit('This script cannot be run from the CLI. Run it from a browser.');
}

require_once dirname(__FILE__).'/../app/SymfonyRequirements.php';

最佳答案

如果要删除的文本范围内没有空行,则可以使用更简单的 awk 命令,如下所示:

> cat file.php
<?php

if (!isset($_SERVER['HTTP_HOST'])) {
       exit('This script cannot be run from the CLI. Run it from a browser.');
}

if (!in_array(@$_SERVER['REMOTE_ADDR'], array(
       '127.0.0.1',
           '::1',
           ))) {
       header('HTTP/1.0 403 Forbidden');
           exit('This script is only accessible from localhost:: .');
}
require_once dirname(__FILE__).'/../app/SymfonyRequirements.php';

> awk '{sub(/if *\( *!in_array.*require_once/, "require_once")}1' RS= file.php

输出

<?php
if (!isset($_SERVER['HTTP_HOST'])) {
       exit('This script cannot be run from the CLI. Run it from a browser.');
}
require_once dirname(__FILE__).'/../app/SymfonyRequirements.php';

更新:这是一个 gnu-awk 版本,也可以处理空行:

awk '{sub(/if *\( *!in_array.*/, "") }1' RS='\n\n' file

关于regex - 我如何在 sed 的正则表达式中包含换行搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21326443/

相关文章:

javascript - 如何在 javascript 中使用正则表达式引用所有变量名称

Java 字符串/正则表达式替换

regex - 如何使用sed用逗号替换空格?

regex - Sed 通过第一个匹配参数替换输入

linux - 需要帮助在 Linux 终端中使用 sed 编辑多个文件

javascript - 将常规 json 转换为 d3.js 的 flare.json?

正则表达式:排除尾随 .0 但包含所有字符串

Linux:如何防止文件支持的内存映射导致访问错误(SIGBUS 等)?

linux - 为所有内核模块添加对符号的支持

linux - 我无法从 Windows 主机访问在 VM 上运行的 Django 服务器