I am writing script that grep the class name of java file containing multiple class, if it contains main function.
Example: My file contain text.txt
class Parent
{
public void p1()
{
System.out.println("Parent method");
}
}
public class Child extends Parent {
public static void main(String[] args)
{
Child cobj = new Child();
cobj.c1(); //method of Child class
cobj.p1(); //method of Parent class
}
public void c1()
{
System.out.println("Child method");
}
}
Output will be: Child because it conatins main function. I analyze the pattern and grep two line before the pattern main found in a file.
My script:
grep -B 2 "public static void main" "text.txt" > sample.txt
filen=$(grep -oP '(?<=class )[^ ]*' sample.txt)
echo $filen
But my approach gets wrong if code contains like:
class Parent
{
public void p1()
{
System.out.println("Parent method");
}
}
public class Child extends Parent {
public void c1()
{
System.out.println("Child method");
}
public static void main(String[] args)
{
Child cobj = new Child();
cobj.c1(); //method of Child class
cobj.p1(); //method of Parent class
}
}
Please help me in finding correct approach.