How do I append some text at the end of a file using Ant?

筅森魡賤 提交于 2020-01-12 11:42:44

问题


In one of the configuration files for my project I need to append some text. I am looking for some options to do this using Ant.

I have found one option - to find something and replace that text with the new text, and the old values. But it does not seems to be promising, as if in future someone changes the original file the build will fail.

So, I would like my script to add the text at the end of the file.

What options do I have for such a requirement?


回答1:


Use the echo task:

<echo file="file.txt" append="true">Hello World</echo>

EDIT: If you have HTML (or other arbitrary XML) you should escape it with CDATA:

<echo file="file.txt" append="true">
<![CDATA[
  <h1>Hello World</h1>
]]>
</echo>



回答2:


Another option would be to use a filterchain.

For example, the following will append file input2.txt to input1.txt and write the result to output.txt. The line separators for the current operating system (from the java properties available in ant) are used in the output file. Before using this you would have to create output2.txt on the fly I guess.

<copy file="input1.txt" tofile="output.txt" >
    <filterchain>
        <concatfilter append="input2.txt" />
        <tokenfilter delimoutput="${line.separator}" />
    </filterchain>
</copy>



回答3:


The concat task would look to do it as well. See http://ant.apache.org/manual/Tasks/concat.html for examples, but the pertinent one is:

<concat destfile="README" append="true">Hello, World!</concat>



回答4:


I found the other answers useful, but not giving the flexibility I needed. Below is an example of writing echos to temp file that can be used as a header and footer, then using concatenation to wrap an xml document.

    <!-- Make header and footer for concatenation -->
    <echo file="header.txt"  append="true">
        <![CDATA[
            <?xml version='1.0' encoding='UTF-8'?>
            <!DOCTYPE foo ...>
        ]]>
    </echo>
    <echo file="footer.txt"  append="true">
        <![CDATA[
            </foo>
        ]]>
    </echo>

    <concat destfile="bigxml.xml">
        <fileset file="header.txt" />
        <fileset file="bigxml-without-wrap.xml" />
        <fileset file="footer.txt" />
    </concat>
    <delete file="header.txt"/>
    <delete file="footer.txt"/>


来源:https://stackoverflow.com/questions/3732583/how-do-i-append-some-text-at-the-end-of-a-file-using-ant

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!