ant: how to compare contents of two files

2019-04-21 11:54发布

I want to compare the contents of two files (say file1.txt,file2.txt) using ANT.

if files content are same then it should set some 'property' to true, if contents are not same then it should set the 'property' as false.

Can anyone suggest me any ANT task that can do this.

Thanks in advance.

标签: ant
2条回答
淡お忘
2楼-- · 2019-04-21 12:34

I am in the same situation to compare two files and switch into different targets depending on files match or files mismatch...

Heres the code:

<project name="prospector" basedir="../" default="main">

<!-- set global properties for this build -->
<property name="oldVersion" value="/code/temp/project/application/configs/version.ini"></property>
<property name="newVersion" value="/var/www/html/prospector/application/configs/version.ini"></property>

<target name="main" depends="prepare, runWithoutDeployment, startDeployment">
    <echo message="version match ${matchingVersions}"></echo>
    <echo message="version mismatch ${nonMatchingVersion}"></echo>
</target>

<target name="prepare">

    <!-- gets true, if files are matching -->
    <condition property="matchingVersions" value="true" else="false">
        <filesmatch file1="${oldVersion}" file2="${newVersion}" textfile="true"/>
    </condition>

    <!-- gets true, if files are mismatching -->
    <condition property="nonMatchingVersion" value="true" else="false">
        <not>
            <filesmatch file1="${oldVersion}" file2="${newVersion}" textfile="true"/>
        </not>
    </condition>

</target>

<!-- does not get into it.... -->
<target name="startDeployment" if="nonMatchingVersions">
    <echo message="Version has changed, update gets started..."></echo>
</target>

<target name="runWithoutDeployment" if="matchingVersions">
    <echo message="Version equals, no need for an update..."></echo>
</target>

The properties are correct and change on changing file contents. the task for nonMatchingVersions never gets started.

查看更多
成全新的幸福
3楼-- · 2019-04-21 12:46

You can use something like:

<condition property="property" value="true">
  <filesmatch file1="file1"
              file2="file2"/>
</condition>

This will set the property only if the files are the same. You can then check for the property, using

<target name="foo" if="property">
...
</target>

This is available in ant, with no added dependency, see here for other conditions.

查看更多
登录 后发表回答