ANT使用带属性的文件替换指定文件中的字符串

时间:2013-04-13 12:00:05

标签: ant properties replace

我在文件dev.properties中有一个属性,它们看起来像这样:

test.url=https://www.example.com/
[...]

在项目文件中有一个令牌[[test.url]],我想用https://www.example.com/替换它。我只想在dev.properties中定义所有标记并在构建脚本中使用它们,但不修改构建脚本,我想在* .php,* .html等指定文件中替换这些标记。

有人可以给我一些建议怎么做吗?感谢。

3 个答案:

答案 0 :(得分:3)

试试这个:

<copy file="input.txt" tofile="output.txt">
   <filterchain>
   <replaceregex pattern="\$\{" replace="{" />
   <filterreader classname="org.apache.tools.ant.filters.ReplaceTokens">
        <param type="propertiesfile" value="properties.txt"/>
        <param type="tokenchar" name="begintoken" value="{"/>
        <param type="tokenchar" name="endtoken" value="}"/>
    </filterreader>
    </filterchain>
</copy>

在这里成立:Ant replace token from properties file

答案 1 :(得分:1)

在以下Ant脚本中,将src-root属性替换为包含标记化文件的根目录:

<project name="ant-replace-tokens-with-copy-task" default="run">
    <target name="run">
        <!-- The <copy> task cannot "self-copy" files. So, for each -->
        <!-- matched file we'll have <copy> read the file, replace the -->
        <!-- tokens, and write the result to a temporary file. Then, we'll -->
        <!-- use the <move> task to replace the original files with the -->
        <!-- modified files. -->
        <property name="src-root" location="src"/>
        <property name="filtered-file.extension" value="*.filtered-file"/>

        <copy todir="${src-root}">
            <fileset dir="${src-root}">
                <include name="**/*.html"/>
                <include name="**/*.php"/>
            </fileset>
            <globmapper from="*" to="${filtered-file.extension}"/>
            <filterchain>
                <filterreader classname="org.apache.tools.ant.filters.ReplaceTokens">
                    <param type="propertiesfile" value="dev.properties"/>
                </filterreader>
            </filterchain>
        </copy>

        <move todir="${src-root}">
            <fileset dir="${src-root}" includes="**"/>
            <globmapper from="${filtered-file.extension}" to="*"/>
        </move>
    </target>
</project>

答案 2 :(得分:1)

您指定不想编辑构建脚本,因此此答案不符合条件,但可能对其他读者仍然有用。

如果您愿意编辑目标文件以使用格式$ {test.url}而不是[[test.url]],那么ExpandProperites将是一个很好的选择。