Question

I want to make an ant target that can replace the content of a file (or more) that does not starts with a defined pattern. Is there a solution for this using ant and replaceregexp ? Or an alternative to this? Example:

  • I have file boo.txt that has the text: "this is boo".
  • Also I have the file foo.txt that has the text: "just foo".

I want to change the text for the foo.txt to: "this just foo"

Was it helpful?

Solution

Probably a case of cooking up a suitable regular expression with captures.

This one appears to work for the example you give.

<property name="prefix" value="this " />
<replaceregexp flags="s" match="^(${prefix})?(.*)" replace="${prefix}\2">
    <fileset dir="files" />
</replaceregexp>
  • The files are specified using a fileset - here all files in the files directory.
  • The prefix we want to optionally add is this, which is stored in a property, as we need to mention it in two places.
  • The flags="s" setting ensures that we treat the file as a single string for match purposes (rather than matching each line).
  • The regular expression looks for the prefix string in the file, and stores it in capture \1 - which is discarded.
  • The rest of the string is in capture \2.
  • Replace with the prefix string, followed by capture \2.

You might think of it as always adding the prefix, but after taking the prefix away if it's already there...except that the replaceregexp task will not write the file unless if differs from the existing.

OTHER TIPS

this is just a partial answer.. I'm not sure if its correct but at least maybe can give you some direction

for this you need ant-contrib

    <property name="folder.name" value="some-folder-name" />
    <property name="text.substitution" value="this " />

    <target name="main">
       <foreach target="target2" param="file_path"> 
          <path> 
             <fileset dir="${folder.name}" casesensitive="no" /> 
          </path> 
       </foreach>
    </target>

<target name="target2">
    <loadfile property="message" srcFile="${file_path}"/>
        <!-- f message doesnt have text.substitution at the begging -->
        <!-- not sure if this is correct regex -->
        <propertyregex property="myprop" input="${message}" 
                      regexp="([^b]+)" select="\0" casesensitive="false" /> 
    <if>
        <equals arg1="${myprop}" arg2="{text.substitution}" />      
    <then>
        <concat destfile="foo.txt" append="true">${text.substitution} </concat>  
    </then>
    </if>
</target>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top