Kas*_*ara 7 command-line bash files java find
我是 linux 新手,对 linux 命令知之甚少。
我的情况是,我在一个目录中有很多具有不同包名的 java 源文件。
我想将所有这些 java 源文件移动到它们各自的包目录中。
在任何java源文件中,第一行是package语句,前面可能有也可能没有注释。
所以我想要的是编写一个 shell 脚本来解析当前目录中所有 .java 文件的包行,然后将该 java 文件移动到其各自的包目录中。
现在的情况:
directory1
|- Class1.java (package : com.pkgA)
|- Class2.java (package : com.pkgB)
|- Class3.java (package : com.pkgC.subpkg)
Run Code Online (Sandbox Code Playgroud)
我想要的是:
directory1
|- src
|- com
|- pkgA
|- Class1.java
|- pkgB
|- Class2.java
|- pkgC
|- subpkg
|- Class3.java
Run Code Online (Sandbox Code Playgroud)
示例源文件:
//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");
}
}
Run Code Online (Sandbox Code Playgroud)
#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
Run Code Online (Sandbox Code Playgroud)