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

时间:2015-08-04 15:09:48

标签: bash sed

我尝试用字符串替换一行,但从unknown option to s'收到unterminated s' commandsed错误。使用/以外的符号(同时尝试@#)无效。

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是缩小的来源,不应包含任何换行符。

2 个答案:

答案 0 :(得分:0)

就出了什么问题而言:

  • jquery.min.js包含@#个字符,因此这两个字符都不是安全的非转义字。
  • 即使您在外部sed使用jquery.min.js/上的@操作也会逃避sed秒实例

    要解决此问题,您可以更改

    file_content=$(sed 's:/:\\/:g' jquery.js)
    

    ...到...

    file_content=$(sed 's:@:\\@:g' jquery.js)
    

此外,如果您没有删除带有许可信息的评论的第一行,则替换文件实际上只有一行。在sed命令中放置未转义的换行符会终止它。

简单的答案是不要使用sed。例如,考虑gsub_literaldefined in BashFAQ #21

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;
    }
  '
}

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

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

答案 1 :(得分:0)

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

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
相关问题