I'm trying to figure out the best way to open an existing file and replace all strings that match a declared string with a new string, save it then close.
Suggestions ?
Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace. It tells sed to find all occurrences of 'old-text' and replace with 'new-text' in a file named input.txt.
The fastest way would be to allocate a new string that is strlen (s) - strlen (word) + strlen (rpwrd) + 1 . Then use the strstr function to find the word to be replaced and copy up to that point into a new string, append the new word, then copy the rest of the original sentence into a new string.
Can be done in one line:
File.WriteAllText("Path", Regex.Replace(File.ReadAllText("Path"), "[Pattern]", "Replacement"));
If you're reading large files in, and you string for replacement may not appear broken across multiple lines, I'd suggest something like the following...
private static void ReplaceTextInFile(string originalFile, string outputFile, string searchTerm, string replaceTerm) { string tempLineValue; using (FileStream inputStream = File.OpenRead(originalFile) ) { using (StreamReader inputReader = new StreamReader(inputStream)) { using (StreamWriter outputWriter = File.AppendText(outputFile)) { while(null != (tempLineValue = inputReader.ReadLine())) { outputWriter.WriteLine(tempLineValue.Replace(searchTerm,replaceTerm)); } } } } }
Then you'd have to remove the original file, and rename the new one to the original name, but that's trivial - as is adding some basic error checking into the method.
Of course, if your replacement text could be across two or more lines, you'd have to do a little more work, but I'll leave that to you to figure out. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With