【问题标题】:how to escape this below sequence inorder to replace the text using sed in shell script?如何转义下面的序列,以便在 shell 脚本中使用 sed 替换文本?
【发布时间】:2012-07-09 18:55:15
【问题描述】:

找到 /cygdrive/c/xampp/htdocs/news4u -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' {} \;

这会导致错误sed: -e expression #1, char 93: unknown option tos'`

我正在使用 windows 并使用 'cygwin' 来运行 shell 脚本。

如何解决这个问题,单引号应该被转义,因为它再次被单引号括起来?

【问题讨论】:

    标签: shell sed replace


    【解决方案1】:

    sed 正则表达式中的/ 转义(例如此处:google-analytics.com/ga.js)或使用其他分隔符(例如s^^^ 而不是s///)。

    【讨论】:

    • 我用过find /cygdrive/c/xampp/htdocs/news4u/apps/frontend/modules/alerts/templates -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 {} \;
    • 我逃脱了/,但它不起作用。还有什么要改的?
    • 你不仅要逃避/,还要逃避'。最好不要转义/,而只是使用其他字符作为s的分隔符。
    【解决方案2】:

    如 Igor 所述,要转义 /,您可以使用另一个分隔符。

    喜欢

    echo //// | sed 's@////@====@'
    

    但是有很多'也需要转义。

    至少有两种方式:

    第一个:

    echo "111'222\"333" | sed 's/1'\''2/___/;s/2"3/__/;'
    

    第二个:

    echo "111'222" | sed "s/1'2/___/;s/2\"3/__/;"
    

    你不能像'\'' 一样逃避',因为' 之间的内容绝对不重要。转义字符在那里不起作用。因此,您首先需要让转义字符与从' 转义一起工作,然后才使用它。因此我们使用''\''' 构造。 但是转义字符在 "" 中可以正常工作,因此您可以使用 "\""

    find /cygdrive/c/xampp/htdocs/news4u/apps/frontend/modules/alerts/templates \
    -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" {} \;
    

    应该可以正常工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-29
      相关资源
      最近更新 更多