我有一个包含多个模块的大型 java 项目,该项目的文件分别位于module1
, module2
... 文件夹中。现在我想将目录重组为 maven/gradle 友好模式,因此所有 .java 文件都在文件夹中MODULE_NAME\src\main\java\
,所有非 java 文件都在MODULE_NAME\src\main\resources\
文件夹中。
cd /home/MYUSER/oldproject
find . -type f -name *.java -print | exec `sed 's:^./\([a-z0-9\-]*\)/\(.*\)/\([a-zA-Z0-9_-]*.java\):mkdir -p /home/MYUSER/project/\1/src/main/java/\2:'`
该命令很好地创建了所需的文件夹(包),但是执行时
find . -type f -name *.java -print | exec `sed 's:^./\([a-z0-9\-]*\)/\(.*\)/\([a-zA-Z0-9_-]*.java\):mv \0 /home/MYUSER/project/\1/src/main/java/\2/:'`
我收到很多消息错误:
mv: cannot stat 'mv': No such file or directory
mv: cannot stat '/home/MYUSER/project/module1/src/main/java/com/apackage/': No such file or directory
当包存在时,我的许多文件只是移动到不相关的模块中。
有人可以帮我解决这个问题吗?
为了在正则表达式中更清楚地表达出来s:^./\([a-z0-9\-]*\)/\(.*\)/\([a-zA-Z0-9_-]*.java\)
,第一个 capture ( \([a-z0-9\-]*\)
) 获取模块,第二个 capture ( \(.*\)
) 获取 java 包,第三个 capture ( \([a-zA-Z0-9_-]*.java\)
) 获取类名。
文件示例列表:
./oldproject/module1/com/mycompany/dir1/dir2/dir3/Class1.java
./oldproject/module1/com/mycompany/dir1/dir4/Class2.java
./oldproject/module2/com/mycompany/dir5/dir6/dir7/dir8/Class3.java
./oldproject/module2/com/mycompany/dir5/dir6/File1.txt
./oldproject/module2/META-INF/File2.txt
我希望他们成为
./project/module1/src/main/java/com/mycompany/dir1/dir2/dir3/Class1.java
./project/module1/src/main/java/com/mycompany/dir1/dir4/Class2.java
./project/module2/src/main/java/com/mycompany/dir5/dir6/dir7/dir8/Class3.java
./project/module2/src/main/resources/com/mycompany/dir5/dir6/File1.txt
./project/module2/src/main/resources/META-INF/File2.txt
模块名称正则表达式\([a-z0-9\-]*\)
包名称(中间文件夹)正则表达式\([a-z0-9_]*\)
(但可以是多个嵌套包)类名称正则表达式\([a-zA-Z0-9_-]*.java\)
更新:看来我的sed
which 生成mv
命令 concat 所有命令,这就是问题(它们之间没有新行),所以看起来 exec 不会一一执行每个 sed 的输出。那么问题是 mkdir 是如何工作的?
答案1
尝试这个:
cd /home/MYUSER/
shopt -s globstar # required in bash for recursion, not needed by zsh
for f in **/*.java; do
nf=$(sed 's:^oldproject/\([a-z0-9\-]*\)/\(.*\)/\([a-zA-Z0-9_-]*.java\):project/\1/src/main/java/\2/\3:' <<< "$f")
echo install -D "$f" "$nf"
echo rm -f "$f"
done
# clean empty dirs
#find . -type d -exec rmdir {} + 2>/dev/null
#rm -rf oldproject # or this one if it's what you need
echo
如果尝试令人满意,则删除这两个命令。
透明地创建install -D source_file dest_file
所需的整个目录结构mkdir -p
。
输出
install -D oldproject/module1/com/mycompany/dir1/dir2/dir3/Class1.java project/module1/src/main/java/com/mycompany/dir1/dir2/dir3/Class1.java
rm -f oldproject/module1/com/mycompany/dir1/dir2/dir3/Class1.java
install -D oldproject/module1/com/mycompany/dir1/dir4/Class2.java project/module1/src/main/java/com/mycompany/dir1/dir4/Class2.java
rm -f oldproject/module1/com/mycompany/dir1/dir4/Class2.java
install -D oldproject/module2/com/mycompany/dir5/dir6/dir7/dir8/Class3.java project/module2/src/main/java/com/mycompany/dir5/dir6/dir7/dir8/Class3.java
rm -f oldproject/module2/com/mycompany/dir5/dir6/dir7/dir8/Class3.java