首页 > 解决方案 > sed - 如何在文件中的匹配模式之前插入文本

问题描述

我有一个文件 a.html,其内容如下

<script src="one.sample.js"/>
<script src="two.sample.js"/>
<script src="three.sample.js"/>

我想修改上面的

<script src="/web/test/src/one.sample.js"/>
<script src="/web/test/src/one.sample.js"/>
<script src="/web/test/src/one.sample.js"/>

如何有一个通用模式用 sed 一次替换所有出现的事件?

标签: regexstringshellsedreplace

解决方案


输入:

$ more a.html 
<body>
        <script src="one.sample.js" />
        <script src="two.sample.js" />
        <script src="three.sample.js" />
</body>

转型:

$ more htmlScriptConvertor.xslt m
::::::::::::::
htmlScriptConvertor.xslt
::::::::::::::
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output method="xml" indent="yes" />
    <xsl:strip-space elements="*"/>

    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="//script[@src]">
        <script src="{concat('/web/test/src/',@src)}"></script>
    </xsl:template>

</xsl:stylesheet>

如果您需要将转换限制为 javascript 脚本,这将复制除包含src属性的脚本节点之外的所有内容(例如,您可以添加属性值必须以结尾的约束)。.js

输出:

$ xsltproc --html htmlScriptConvertor.xslt a.html
<?xml version="1.0"?>
<html>
  <body>
    <script src="/web/test/src/one.sample.js"/>
    <script src="/web/test/src/two.sample.js"/>
    <script src="/web/test/src/three.sample.js"/>
  </body>
</html>

重定向并保存到a_new.html


推荐阅读