Groovy way to remove file extension?

Jay P. picture Jay P. · Dec 16, 2015 · Viewed 12k times · Source

I'm wondering if there is a "Groovy" way to remove the file extension from a filename.

The current solution relies on the apache commons io package:

import org.apache.commons.io.FilenameUtils

String filename = '/tmp/hello-world.txt'
def fileWithoutExt = FilenameUtils.removeExtension(filename)

Answer

tim_yates picture tim_yates · Dec 16, 2015

You can do something like this:

filename[0..<filename.lastIndexOf('.')]

To remove everything after the last . in the String.

Or the slightly prettier:

filename.take(filename.lastIndexOf('.'))

NB: if a file haven't an extension it will be not matched