首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >sed:用多行文件的内容替换字符串

sed:用多行文件的内容替换字符串
EN

Stack Overflow用户
提问于 2015-08-04 15:09:48
回答 2查看 125关注 0票数 0

我试图用字符串替换一行,但接收来自unknown option to s'unterminated s' commandsed错误。使用/以外的sigils (尝试了@#)没有任何效果。

代码语言:javascript
复制
line='<script type="text/javascript" src="<?php echo $jquery_path ?>jQuery.js"></script>'
file_content=$(sed 's:/:\\/:g' jquery.js) # escape /s in replacement content

sed -i -e "s@$line@$file_content@" ./index.php

jquery.js是缩小的源,不应该包含任何换行符。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-08-04 16:29:09

关于哪里出了问题:

  • jquery.min.js包含@#字符,因此它们都不像未转义的信号那样安全。
  • 您对jquery.min.jsjquery.min.js操作是转义/s,即使在外部sed实例中使用@s。 要解决这个问题,您可能会更改 file_content=$(sed‘s:/:G’jquery.js) ...to... file_content=$(sed‘s:@:@:G’jquery.js)

另外,如果您没有删除带有许可信息的注释的第一行,替换文件实际上并不仅仅是一行。在sed命令中放置未转义的换行符将终止它。

简单的答案是根本不使用sed。例如,考虑一下gsub_literal,作为defined in BashFAQ #21

代码语言:javascript
复制
gsub_literal() {
  # STR cannot be empty
  [[ $1 ]] || return

  # string manip needed to escape '\'s, so awk doesn't expand '\n' and such
  awk -v str="${1//\\/\\\\}" -v rep="${2//\\/\\\\}" '
    # get the length of the search string
    BEGIN {
      len = length(str);
    }

    {
      # empty the output string
      out = "";

      # continue looping while the search string is in the line
      while (i = index($0, str)) {
        # append everything up to the search string, and the replacement string
        out = out substr($0, 1, i-1) rep;

        # remove everything up to and including the first instance of the
        # search string from the line
        $0 = substr($0, i + len);
      }

      # append whatever is left
      out = out $0;

      print out;
    }
  '
}

在您的用例中,这可能如下所示:

代码语言:javascript
复制
gsub_literal \
  '<script type="text/javascript" src="<?php echo $jquery_path ?>jQuery.js' \
  "$(<../my_files/jquery.js)" \
  <index.php >index.php.out && mv index.php.out index.php
票数 0
EN

Stack Overflow用户

发布于 2015-08-04 21:47:42

你自己说过你想替换一个字符串。sed不能在字符串上操作,只能在regexp上操作(请参阅Is it possible to escape regex metacharacters reliably with sed)。另一方面,awk可以对字符串进行操作,所以只需使用awk:

代码语言:javascript
复制
awk -v old='<script type="text/javascript" src="<?php echo $jquery_path ?>jQuery.js"></script>' '
NR == FNR { new = new $0 ORS; next }
$0 == old { $0 = new }
{ print }
' jquery.js index.php
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31812932

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档