Groovy way to remove file extension?

May be overkill in this case but I tend to treat a lot of the commons classes as mixins

String.metaClass.mixin org.apache.commons.io.StringUtils
String.metaClass.mixin org.apache.commons.io.FilenameUtils
etc

This then allows you to

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

Which ones I mixin depends on the requirements of the script but I tend to use this pattern a lot. It enables me to easily use methods I'm used to using without all the static class or import references.


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