简体   繁体   中英

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).

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.

Is there a simple way to do this in all 600 files at once?

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.

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. 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.

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
  2. .bak means make a copy of the input files with the .bak extension before making changes
  3. -p means wrap the program in a loop that grabs a line, runs the program, and prints the line
  4. -e 's/.../.../' means the quoted part is the program to run, and it does a regular expression substitution.
  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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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