简体   繁体   English

替换大量java源文件中的一行

[英]Replacing a line in a large number of java source files

I have around 600 java classes in a project with random names (there is no pattern in their names). 我在一个带有随机名称的项目中有大约600个java类(名称中没有模式)。

I want to replace a particular line from inside these classes with another line. 我想用另一行替换这些类中的特定行。

For eg line inside these files is 例如,这些文件中的行是

System.out.println("Product is: "+myProduct);

and I want to replace that line with 我想用那个替换那一行

System.out.println("Object is: "+myObject);

The above line is just an example showing what I want to achieve. 上面的这一行只是一个展示我想要实现的目标的例子。

I am using RAD 7.5 for development. 我正在使用RAD 7.5进行开发。

Is there a simple way to do this in all 600 files at once? 是否有一种简单的方法可以同时在所有600个文件中执行此操作?

Yes. 是。 By opening the Search - File... dialog box, entering what you want to search for and the file filter you want, and then clicking Replace . 通过打开“搜索 - 文件...”对话框,输入要搜索的内容和所需的文件筛选器,然后单击“ 替换”

No. No access to UNIX system. 不可以访问UNIX系统。

That's your first problem. 那是你的第一个问题。 Install Cygwin so you have a solid shell, and then you can learn how to do batch operations on source code. 安装Cygwin以便拥有可靠的shell,然后您可以学习如何对源代码进行批处理操作。 Being able to grep around easily can make it much easier to learn your way around large code-bases and narrow down the amount of code that is likely to contribute to a thorny problem. 能够grep周围很容易可以使它更容易学习在大型代码库的方式缩小很可能导致一个棘手的问题的代码量。

Once you've got that installed, you can solve your immediate problem with 一旦安装完毕,就可以解决当前的问题

perl -i.bak \
  -pe 's/System.out.println\("Product is: "+myProduct\);/System.out.println("Object is: "+myObject);/' \
  file0.java file1.java ...

Breaking it down: 打破它:

  1. -i means treat the arguments as files to modify in-place -i表示将参数视为要就地修改的文件
  2. .bak means make a copy of the input files with the .bak extension before making changes .bak表示在进行更改之前,使用.bak扩展名复制输入文件
  3. -p means wrap the program in a loop that grabs a line, runs the program, and prints the line -p表示将程序包装在一个循环中,该循环抓取一行,运行程序并打印该行
  4. -e 's/.../.../' means the quoted part is the program to run, and it does a regular expression substitution. -e 's/.../.../'表示引用的部分是要运行的程序,它执行正则表达式替换。
  5. the rest are the files to run it on. 其余的是运行它的文件。

Alternatively, 或者,

find . -name \*.java

should list all the java source files under the current directory. 应该列出当前目录下的所有java源文件。

Assuming that directory doesn't have spaces in its path, you can then do 假设目录的路径中没有空格,那么您可以这样做

find . -name \*.java | xargs perl -i.bak -pe 's/.../.../'

where the ... is the replacement above to run it over all Java sources under the working directory. 其中...是上面的替换,在工作目录下的所有Java源上运行它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM