Groovy way to remove file extension?

I am wondering if there is a โ€œGroovyโ€ way to remove the file extension from the file name.

The current solution is based on the apache commons io package:

import org.apache.commons.io.FilenameUtils String filename = '/tmp/hello-world.txt' def fileWithoutExt = FilenameUtils.removeExtension(filename) 
+8
file-extension groovy
source share
2 answers

You can do something like this:

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

To delete everything after the last . in line.

Or a little prettier:

 filename.take(filename.lastIndexOf('.')) 
+15
source share

It might be redundant in this case, but I tend to treat many publicity classes like mixins

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

It allows you

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

Which one I mix depends on the requirements of the script, but I often use this template. This allows me to easily use the methods that I use to use without all the static classes or import references.

+2
source share

All Articles