How do I append some text at the end of a file usi

2019-04-03 08:10发布

问题:

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"/>


标签: ant append