I have many Java source files which I need to change their package line with a custom one depending on the current directory structure. Some of these files don’t have package lines, so I would want to replace them.
Say the source file is in directory dirA and the current package header is package mypackage.myimpl;. I would like to change it to package dirA;. In the case where the source file had no package statement at all, I would like to add the package dirA; line.
Is there an elegant one or two-liner in sed or awk?
Assuming
$INFILEis the name of the file to modify based out of your “package root” (ie: com.example.foo.Bar should be referred to as com/example/foo/Bar.java) then this should do what you want.The one big caveat is that it inserts the package statement as the first line in the file.