如何使用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
相关产品推荐
相关产品推荐

