You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Sed添加特殊字符?在xx.html中插入代码至</body>前

sed插入含PHP代码到HTML文件的转义问题解决

通用解决方案(匹配</body>行前插入,无需固定行号)

针对GNU sed(Linux默认环境):

sed -i '/<\/body>/i secure_token = "<?php echo file_get_contents("token.txt"); ?>"\nfunction getipInfo()' xx.html

针对BSD sed(macOS等环境):

sed -i '' '/<\/body>/i\secure_token = \"<?php echo file_get_contents(\"token.txt\"); ?>\"\nfunction getipInfo()' xx.html

指定行号插入(对应原需求的第102行)

GNU sed版本:

sed -i '102i secure_token = "<?php echo file_get_contents("token.txt"); ?>"\nfunction getipInfo()' xx.html

BSD sed版本:

sed -i '' '102i\secure_token = \"<?php echo file_get_contents(\"token.txt\"); ?>\"\nfunction getipInfo()' xx.html

关键说明

  • 改用双引号包裹sed脚本,避免单引号内复杂转义的混乱;GNU sed支持在i命令后直接加空格和内容,BSD sed则要求i\后紧跟内容
  • 匹配</body>行比固定行号更鲁棒,防止文件内容变更后行号失效
  • 超大文件使用sed操作无性能问题,sed本身就是面向流处理的工具

内容的提问来源于stack exchange,提问作者user20181952

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 05:55:23