7

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");    
    }
}
0
8
#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
1
  • Its working perfectly, as expected. You are genius. Thank you....thank you...so much. – Kashyap Kansara Oct 13 '17 at 13:07
1

Here's a Python version:

#!/usr/bin/env python3
from pathlib import Path
from javalang.parse import parse  # $ pip install javalang

for java_src_path in Path().glob('*.java'):
    tree = parse(java_src_path.read_text())
    package_path = Path('src', *tree.package.name.split('.'))
    package_path.mkdir(parents=True, exist_ok=True)
    java_src_path.replace(package_path / java_src_path.name)

It uses javalang parser, to parse Java source code. I was just interested how it may look like. The regex-based bash version from @RoVo's answer should be fine.

1
  • I can easily come up with source files that break @RoVo's code but should be fine with yours, so this is definitely a valuable addition to this question. – Jörg W Mittag Oct 14 '17 at 6:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.