如何使用sed命令批量更改java包声明?

时间:2021-08-26 00:39:06

Previously, my java package declarations all start with 'zn' like "package zn.tree". Now after I changed the java folder path to remove 'zn' folder, I also want to change all java declarations to remove the prefix 'zn.' in a batch way. For example, I want change "package zn.tree" to "package tree".

以前,我的java包声明都以'zn'开头,比如' package z .tree '。现在,在我更改了java文件夹路径以删除'zn'文件夹之后,我还想更改所有java声明以删除前缀'zn。“成批的。”例如,我想要更改“package zn”。树”到“包树”。

So I decided to use bash script to change all the java files. After I googled, I wrote a script to use 'sed' command to do this job. However, it doesn't work and reports error. I still don't get familiar with the regex in 'sed'. My code is shown below:

所以我决定使用bash脚本修改所有java文件。在我搜索之后,我编写了一个脚本使用“sed”命令来完成这项工作。但是,它不起作用并报告错误。我还是不太熟悉sed中的regex。我的代码如下所示:

#! /bin/bash
# change package declaration in batch way
for path in $(find $1 -type f -name "*.java"); do
        sed -i "" 's/\<zn/.\>//g' $path
done

Hope someone could give me some clues. Thank you.

希望有人能给我一些线索。谢谢你!

2 个解决方案

#1


3  

If I understand your question, you could do it with a one liner like,

如果我能理解你的问题,你可以用一句话,

find . -type f -name '*.java' -exec sed -i 's/^package zn\./package /1' {} \;

That will execute the sed command and instruct it to edit in-place on every matching file. Note that I assume you want to match the first line starting with "package zn." and replace it with "package " once.

这将执行sed命令,并指示它在每个匹配文件上就地编辑。注意,我假设您希望匹配以“package zn.”开头的第一行,并将其替换为“package”。

#2


0  

Using the refactoring feature of an IDE such as Eclipse, IntelliJ or Netbeans will save you a lot of time for those needs. In IntelliJ, you would just create your new package and drag-and-drop your classes from the old package to the new one.

使用IDE的重构特性(如Eclipse、IntelliJ或Netbeans)可以为这些需求节省大量时间。在IntelliJ中,你只需创建你的新包,然后拖拽你的类从旧包到新包。

#1


3  

If I understand your question, you could do it with a one liner like,

如果我能理解你的问题,你可以用一句话,

find . -type f -name '*.java' -exec sed -i 's/^package zn\./package /1' {} \;

That will execute the sed command and instruct it to edit in-place on every matching file. Note that I assume you want to match the first line starting with "package zn." and replace it with "package " once.

这将执行sed命令,并指示它在每个匹配文件上就地编辑。注意,我假设您希望匹配以“package zn.”开头的第一行,并将其替换为“package”。

#2


0  

Using the refactoring feature of an IDE such as Eclipse, IntelliJ or Netbeans will save you a lot of time for those needs. In IntelliJ, you would just create your new package and drag-and-drop your classes from the old package to the new one.

使用IDE的重构特性(如Eclipse、IntelliJ或Netbeans)可以为这些需求节省大量时间。在IntelliJ中,你只需创建你的新包,然后拖拽你的类从旧包到新包。