First, you want to find the main method, the file basename is the class name
CLASS=$(basename -s .java $(grep -l 'public static void main' *.java)) Then, extract all the imports, sort them, and use uniq. Assuming there are no wildcard imports that match other imports.
sed -n '/^[ \t]*import /p' *.java | sort | uniq > $CLASS.java.output Then process Java files, extracting imports and packages:
grep -hv '^[ \t]*import \|^[ \t]*package' *.java | sed -e 's/public class/class/g;s/public interface/interface/g' >>$CLASS.java.output another way, pure sed:
sed -e '/^[ \t]*\(import\|package\)/d;s/public class/class/g;s/public interface/interface/g' .java >>$CLASS.java.output Then you want to revert your public class
sed -i "s/class $CLASS/public class $CLASS/g" $CLASS.java.output Note that you do not have to use bash in your shebang (#!/bin/sh is good enough), because you do not have any bashisms, here.
Also note, you do not have to cat-pipe to sed, sed -e 's/.../.../' *.java is the same as cat *.java | sed -e 's/.../.../', however, you only have sed running in the first solution, not cat and sed - lessfewer processes is always better.