Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace string in file

Tags:

I'm looking for a way to replace a string in a file without reading the whole file into memory. Normally I would use a Reader and Writer, i.e. something like the following:

public static void replace(String oldstring, String newstring, File in, File out)     throws IOException {      BufferedReader reader = new BufferedReader(new FileReader(in));     PrintWriter writer = new PrintWriter(new FileWriter(out));     String line = null;     while ((line = reader.readLine()) != null)         writer.println(line.replaceAll(oldstring,newstring));      // I'm aware of the potential for resource leaks here. Proper resource     // handling has been omitted in the interest of brevity     reader.close();     writer.close(); } 

However, I want to do the replacement in-place, and don't think I can have a Reader and Writer open on the same file concurrently. Also, I'm using Java 1.4, so dont't have access to NIO, Scanner, etc.

Thanks, Don

like image 637
Dónal Avatar asked Jun 30 '10 08:06

Dónal


People also ask

How do you replace a line in a file using bash?

The 'sed' command is used to replace any string in a file using a bash script. This command can be used in various ways to replace the content of a file in bash. The 'awk' command can also be used to replace the string in a file.

How do I replace a string that contains multiple files in a directory?

s/search/replace/g — this is the substitution command. The s stands for substitute (i.e. replace), the g instructs the command to replace all occurrences.


1 Answers

"In place" replacing usually isn't possible for files, unless the replacement is exactly the same length as the original. Otherwise the file would need to either grow, thus shuffling all later bytes "to the right", or shrink. The common way of doing this is reading the file, writing the replacement to a temporary file, then replacing the original file with the temporary.

This also has the advantage that the file in question is at all times either in the original state or in the completely replaced state, never in between.

like image 125
Jakob Borg Avatar answered Sep 24 '22 04:09

Jakob Borg