Solution in Groovy language 2.4.4
Download Groovy: http://www.groovy-lang.org/download.html
Java must be installed for Groovy to work.
def folders = new File("/home/cantoni/Documents/Teste")
def destFolder = "/home/cantoni/Documents/Teste2/"
folders.listFiles().groupBy {it.name.substring(0,3)}.each {group ->
def folder = new File(destFolder + group.key)
if (!folder.exists()) new File(destFolder + group.key).mkdir()
def files = group.value
files.each {
it.renameTo(folder.absolutePath + "/" + it.name)
}
}
Code explained
The above code goes through all the files that are inside the folder specified by the variable folders, then group them by the first 3 characters that make up the name.
folders.listFiles().groupBy {it.name.substring(0,3)}
The result of grouping is a map, where the key is the first 3 characters and the value is the files that have these first 3 characters in the name. Example:
AAA-123.TXT
AAC-234.TXT
AAA-553.TXT
AAC-001.TXT
CCC-987.TXT
The map would look like this:
AAA: [AAA-123.TXT,AAA-553.TXT], AAC: [AAC-234.TXT,AAC-001.TXT], CCC: [CCC-987.TXT]
From this, create the folder (if it does not exist), inside the folder specified by the variable destFolder. The name of each folder is the key of the map, that is, the first three characters.
def folder = new File(destFolder + group.key)
if (!folder.exists()) new File(destFolder + group.key).mkdir()
Created the folder, it’s time to move the files. The value map are the files that share the same key. Thus, just retrieve them, scroll through them and, for each, perform the procedure of moving them from the current location to the destination folder, destFolder.
def files = group.value
files.each {
it.renameTo(folder.absolutePath + "/" + it.name)
}
Heed
This code has been tested on Linux and works. Test it with other files before you run it with your production files. Can’t be too careful.
Does this need to be done in C or does the language not matter? Another question, Linux or Windows?
– cantoni
Any language, it is important to resolve this problem.. Windows
– Thiago Benine