How to merge files into folders, based on their prefixes?

-2

I have thousands of files in hand that have common prefixes in their names, something like:

[Prefix Example 1]

  • ABC-1.mp4
  • ABC-2.mp4
  • ABC-3.mp4
  • [...]
  • ABC-999.mp4

[Example 2 prefix]

  • AAA-1.mp4
  • AAA-2.mp4
  • AAA-3.mp4
  • [...]
  • AAA-999.mp4

However, there are thousands of files and thousands of prefixes in common. I would like to join the files that have the same prefix in the same folder, the folder would have the name of the prefix, for example:

  • ABC (would be the folder name)
    • ABC-1.mp4
    • ABC-2.mp4
    • ABC-3.mp4
    • [...]
    • ABC-999.mp4
  • AAA (would be the folder name)
    • AAA-1.mp4
    • AAA-2.mp4
    • AAA-3.mp4
    • [...]
    • AAA-999.mp4
asked by anonymous 02.08.2015 / 16:36

1 answer

1

Solution in Groovy language 2.4.4

Download Groovy: link

You must have Java 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)
    }
}

Explained code

The code above, traverses all files that are within the folder specified by the folders variable, then groups them by the first 3 characters that make up the name.

folders.listFiles().groupBy {it.name.substring(0,3)}

The result of the collation is a map, where the key is the first 3 characters and the value are 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, the folder is created (if it does not exist), inside the folder specified by the destFolder variable. The name of each folder is the map key, ie the first three characters.

    def folder = new File(destFolder + group.key)
    if (!folder.exists()) new File(destFolder + group.key).mkdir()

Created folder, it's time to move the files. The value of the map are the files that share the same key. So, just retrieve them, go through them, and for each one, 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)
    }

Attention

This code has been tested on Linux and it works. Test other files before running it with your production files. Caution is never too much.

    
02.08.2015 / 22:36