Ubuntu – How to move all java source files to their respective package directory

bashcommand linefilesfindjava

I am new to linux and don't know much about linux commands.

My scenario is that, I have so many java source files with different
package name in a directory.

I want to move all these java source files to their respective package
directory.

In any java source file, the first line is package statement, which may
or may not be preceeded by comment.

So what I want is to write a shell script that parse the package line for
all .java files in current directory and then move that java file in
its respective package directory.

Current situation:

directory1
|- Class1.java (package : com.pkgA)
|- Class2.java (package : com.pkgB)
|- Class3.java (package : com.pkgC.subpkg)

What I want:

directory1
|- src
   |- com
      |- pkgA
         |- Class1.java
      |- pkgB
         |- Class2.java
      |- pkgC
         |- subpkg
            |- Class3.java

Example source file:

//This is single line comment
/* This is multi line comment
 * Any of these style comment may or may not be present
 */

package com.pkgA;

public class Class1 {
    public static void main(String[] args) {
        System.out.println("Hello");    
    }
}

Best Answer

#Loop through the java files
for f in *.java; do

    # Get the package name (com.pkgX)
    package=$(grep -m 1 -Po "(?<=^package )[^; ]*" "$f")

    # Replace . with / and add src/ at the beginning
    target_folder="src/${package//./\/}"

    # Create the target folder
    mkdir -p "$target_folder"

    # move the file to the target folder
    mv "$f" "$target_folder"

done