簡體   English   中英

如果匹配字符串存在且未注釋,則 Sed 命令替換為一行

[英]Sed command to replace to a line if a matching string is there and it is not commented

我需要搜索具有字符串的文件,並且只有在沒有注釋的情況下才用新行替換整行。 實際情況是,僅當未注釋包含語句時,我才需要用新文件替換文件的包含。

例子:

include("../mytest.php");
// include("../mytest.php");

預期結果:

require_once("mytestnew.php");
// include("../mytest.php");

我嘗試了以下一些在網絡上不同位置找到的 sed 命令:

sed -i '/^[\t]*\/\/.*/!/include.*mytest.php/c\require_once("mytestnew.php");' file.php
sed -i '/^[\t]*\/\/.*/!{include.*mytest.php/c\require_once("mytestnew.php");}' file.php
sed -i '/^[\t]*\/\/.*/b;include.*mytest.php/c\require_once("mytestnew.php");' file.php
sed -i '/^[\t]*\/\/.*/!s/include.*mytest.php/c\require_once("mytestnew.php");/g' file.php

在大多數其他情況下,要么我收到意外的 { 或 s 等錯誤,要么結果不符合預期。

嘗試

sed 's#^[ \t]*include("../mytest.php");#require_once("../mytestnew.php");#' inputfile

如果要在未注釋include行中保留前導空格,請嘗試:

sed 's#^\([ \t]*\)include("../mytest.php");#\1require_once("../mytestnew.php");#' inputfile

您是否嘗試過:

sed 's|^include("../mytest.php");|require_once("mytestnew.php");|g' file.php

使用轉義字符后我得到了它:

sed -i 's#^[\t]*include.*mytest.php");#require_once("\.\.\/mytestnew.php");#' file.php

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM