【问题标题】:How to replace the following text using sed?如何使用 sed 替换以下文本?
【发布时间】:2012-07-10 10:39:04
【问题描述】:

你好我想替换document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));

(function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);})();

在所有情况下...

所以我使用了下面的代码。

find /cygdrive/c/xampp/htdocs/news -type f -exec sed -i s#document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));#(function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);})();#g {} \;

但它并没有取代。逃跑有问题吗?

谢谢

【问题讨论】:

  • Shell 将扩展双引号和单引号字符。你必须引用它们。
  • 此外,“.” (点)在正则表达式中具有特殊含义。不过,在这种特殊情况下,它不太重要。
  • @fork0,这无济于事,shell 也会进行分词。空格需要转义(或引用)

标签: shell sed replace


【解决方案1】:

您需要将参数引用到 sed,并转义任何嵌套引号。否则:

s#document.write(unescape("%3Cscript src='" + gaJsHost +  ...

将被 shell 分解成单独的单词,而不是作为单个参数传递给 sed。

您需要将整个 sed 脚本(s#from#to# 部分)括在引号中,我会选择单引号,然后将脚本中的每个 ' 替换为 \'

(另外,你为什么用find -exec而不是我的suggested?)

【讨论】:

    【解决方案2】:

    好吧,第一步是单独检查sed 命令:

    bash:意外标记 `(' 附近的语法错误

    您必须将 sed 命令放在单引号或双引号中,以便将其作为单个参数传递给 sed 应用程序 's#docum....'。如果单引号中有单引号,或者双引号中有双引号,则必须对其进行转义。

    请注意,该命令看起来很丑陋,不是真正可读或可维护的,我会使用 python 或 ruby​​ 有特殊引号的地方,这将有助于克服字符串转义的问题...

    【讨论】:

      【解决方案3】:

      sed -i "s/^document.write(unescape(.*;$/(function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga. async = true;ga.src = ('https:' == document.location.protocol ?'https://ssl':'http://www') + '.google-analytics.com/ga.js' ;var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);})();/" example.txt

      【讨论】:

      • 为什么不使用不同的分隔符,例如s#a#b#s,a,b, 来避免leaning toothpick syndrome
      • 由于 Javascript 代码通常在它的某个地方有 '#' 或 ',',而且你必须逃避它。我同意你的一般情况,但我认为在这个情况下,直接的方法可能更容易理解。我发现记住转义“/”比记住为其他字符转义要容易。
      • 选择一个不在字符串中的分隔符,您不需要转义任何内容。在替换 URL 位时,选择在 URL 中频繁出现的分隔符只会使其变得比需要的更难。无论如何 +1。
      • @Kuf 我用的和你给的一样。对于某些文件,它的 ID 不变。如果我为此 grep,我得到 0 计数。 $ grep -c 'document.write(unescape(*;$' /cygdrive/c/xampp/htdocs/news4u/apps/frontend/modules/docs/templates/vodafone-deals.htm
      • 我不确定我得到了你,你的意思是它不会改变吗?你能给我一个例子,它不会改变或再次解释你的意思是什么......
      【解决方案4】:

      即使不是直接答案,也可以使用“rpl”工具进行此类替换。 看起来你使用的是cygwin,因此你可以找到一个win32端口here

      【讨论】:

        猜你喜欢
        • 2011-11-25
        • 1970-01-01
        • 2021-09-25
        • 2014-12-22
        • 2022-11-14
        • 1970-01-01
        • 1970-01-01
        • 2012-07-09
        相关资源
        最近更新 更多