基本上我有一个文本文件,我想在其中替换多行的行
我正在使用这个代码
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/