Remove Duplicate Dependencies in Maven Pom

Viewed 18724

I would like to remove duplicate dependencies in maven pom.xml.

I would like answers to multiple tools Linux, Notepad++, Netbeans, Intellij ...even...VIM,etc.

example (I can obvious delete but I would like a search replace answer)

  `<dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-server</artifactId>
        <version>2.7</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-servlet-core</artifactId>
        <version>2.7</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-jetty-http</artifactId>
        <version>2.7</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-moxy</artifactId>
        <version>2.7</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-jetty-http</artifactId>
        <version>2.7</version>
    </dependency>`  

Please write the answer locally links can be frustrating if removed. Thanks.

5 Answers

dependency:analyze-duplicate Analyzes the and tags in the pom.xml and determines the duplicate declared dependencies.

mvn dependency:analyze-duplicate

As the pom.xml is XML you can also use XSLT:

  1. Go to https://www.freeformatter.com/xsl-transformer.html

  2. Use this XSLT:

    <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    
    <xsl:output omit-xml-declaration="yes" indent="yes"/>
    
    <xsl:template match="/*">
        <dependencies>
            <xsl:for-each-group select="dependency" group-by="concat(groupId , '|', artifactId)">
                <xsl:sequence select="."/>
            </xsl:for-each-group>
        </dependencies>
    </xsl:template>
    
    </xsl:stylesheet>
    
  3. Cut the <dependencies> section from you pom.xml as input

  4. Paste the output of the XSLT back into your pom.xml

mvn dependency:list -Dsort=true | grep "^[INFO] " | awk '{print $2}' | cut -f1-4 -d: | sort | uniq | cut -f1-3 -d: | uniq -c | grep -v '^ *1 '

Related