Joshua Fox
Joshua Fox

Reputation: 19665

How can Maven delete all files with a given text-string inside them?

For a certain Maven 'profile' (i.e., a variant of the build), I want to delete files that have a certain text-string inside them. It's easy to list filenames to delete, but in my case, I want the information to be located in (comments in) the files themselves.

How can I do that?

Upvotes: 2

Views: 1797

Answers (2)

Patrice M.
Patrice M.

Reputation: 4319

A variation of @khmarbaise's answer is to do this with the Ant plugin and an Ant scriptlet, which should be more straight-forward than the Groovy snippet. That being said, it all depends on your scripting language of choice, once you've established that you need to script this.

So for instance:

<plugin>
    <artifactId>maven-antrun-plugin</artifactId>
    <executions>
      <execution>
        <phase> <!-- a lifecycle phase --> </phase>
        <configuration>
          <target>

            <delete>
                <!-- here, the 'generated.java.dir' is assumed to be a maven property defined earlier in the pom -->
                <fileset dir="${generated.java.dir}" includes="**/*.java">
                    <contains text="DELETE.ME.IF.YOU.SEE.THIS" casesensitive="no"/>
                </fileset>
            </delete>

          </target>
        </configuration>
        <goals>
          <goal>run</goal>
        </goals>
      </execution>
    </executions>
</plugin>

Note that you can also use the <containsregexp> selector for more complex matches, if needed.

Upvotes: 2

khmarbaise
khmarbaise

Reputation: 97427

I would say the only way would be a groovy script part otherwise i don't see a way for such weird requirement.

<plugin>
    <groupId>org.codehaus.gmaven</groupId>
    <artifactId>gmaven-plugin</artifactId>
    <executions>
        <execution>
            <phase>generate-resources</phase>
            <goals>
                <goal>execute</goal>
            </goals>
            <configuration>
                <source>
def directory = new File("TheFolderYouWouldLikeToDeleteFilesIn")

directory.eachFileRecurse(groovy.io.FileType.FILES) {
   file ->
   def deleteFile = false;
   file.eachLine{ line ->
        if (line.contains("Text String Inside")) {
                deleteFile = true;
        }
   }
   if (deleteFile) {
        println "Deleting " + file
        file.delete()
   }

}

                </source>
            </configuration>
        </execution>
    </executions>
</plugin>

Upvotes: 2

Related Questions