【问题标题】:Using SED to append a string to an existing line of text?使用 SED 将字符串附加到现有文本行?
【发布时间】:2011-03-08 13:45:42
【问题描述】:

我正在尝试使用 linux sed 命令将路径元素附加到 .htaccess 文件中的 RewriteBase。

我已经用这个参数试过了:

#current RewriteBase is "RewriteBase /mypath"
sed -ie 's/RewriteBase\(.*\)/RewriteBase \1\/add/g' .htaccess

结果如下:

addriteBase /mypath

所以 sed 用最后一个字符串覆盖替换字符串的开头。

这是为什么呢?

另一个问题是,当 RewriteBase 只是“/”时,如何防止出现 2 个斜线。

RewriteBase /

会变成

RewriteBase //add

但应该是

RewriteBase /add

有什么办法可以防止这种情况发生吗?如果不是,我可以运行第二个 sed 命令,将所有双斜杠替换为一个。但也许有更优雅的方式来做到这一点。

我将不胜感激。

【问题讨论】:

    标签: regex linux text replace sed


    【解决方案1】:

    如果您只想在该行中添加一些文本,则不需要反向引用。试试这个:

    sed -i.bak 's/^M//g;s|RewriteBase.*|&/add|' .htaccess
    

    特殊的& 字符表示模式空间中匹配的所有内容。

    注意:

    s/^M//g 部分是与 dos2unix 等效的 sed,^M 是通过键入 <ctrl+v><ctrl+m> 创建的。

    【讨论】:

    • 您可以使用\r:sed /\r//(不太可能需要g)来代替Ctrl-v,Ctrl-m。这是第二部分的替代方案:/RewriteBase/ s|$|/add|
    【解决方案2】:

    您看到的是 sed,在结果中包含 \r,使其 看起来 好像文本被卡在了开头。在将文件通过 sed 之前,将文件通过 dos2unix 推送。

    至于第二部分,需要在组外捕获可选的斜线,然后放入/add

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-22
      • 2014-02-25
      • 1970-01-01
      • 1970-01-01
      • 2014-04-12
      • 2015-08-04
      • 2014-06-12
      • 1970-01-01
      相关资源
      最近更新 更多