I'm trying to rename files in a directory using Groovy but I can't seem to understand how it works.
Here is my script:
import groovy.io.FileType
def dir = new File("C:/Users/דודו/Downloads/Busta_Rhymes-Genesis-(Retail)-2001-HHI")
def replace = {
if (it == '_') {
' '
}
}
String empty = ""
dir.eachFile (FileType.FILES) { file ->
String newName = file.name
newName = newName.replaceAll(~/Busta_Rhymes/, "$empty")
newName = newName.replaceAll(~/feat/, "ft")
newName = newName.replaceAll(~/-HHI/, "$empty")
newName = newName.replaceAll(~/--/, "-")
newName = newName.collectReplacements(replace)
file.renameTo newName
println file.name
}
When I run this, the names of the files aren't changed as expected. I'm wondering how could I get this to work.
There are a number of things wrong here:
Your dir
variable is not the directory; it is the file inside the directory that you actually want to change. Change this line:
dir.eachFile (FileType.FILES) { file ->
to this:
dir.parentFile.eachFile (FileType.FILES) { file ->
The renameTo
method does not rename the local name (I know, very counterintuitive), it renames the path. So change the following:
String newName = file.name
to this:
String newName = file.path
Now, for some reason beyond my comprehension, println file.name
still prints out the old name. However, if you look at the actual directory afterwords, you will see that the file is correctly renamed in the directory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With