replace_str_in_file

Function replace_str_in_file 

Source
pub fn replace_str_in_file<P: AsRef<Path>>(
    path: P,
    old_string: &str,
    new_string: &str,
)
Expand description

Replaces all occurrences of a string in a file.

§Arguments

  • path - Path to the file where the replacements will be performed (can be a &str, String, Path, or std::path::PathBuf).
  • old_string - The substring to find and replace in all files.
  • new_string - The replacement string.

§Panics

If some error is encountered while reading from or writing to the file.

§Examples

§Using a string literal

use file_io::{load_file_as_string, replace_str_in_file, save_string_to_file};

// Path to file.
let path: &str = "folder/subfolder_8/file_5.txt";

// Create a file with some content.
save_string_to_file("Hello, world!", path);

// Replace "Hello" with "Goodbye".
replace_str_in_file(path, "Hello", "Goodbye");

// Verify that the content was replaced.
let content = load_file_as_string(path);
assert_eq!(content, "Goodbye, world!");

§Using a Path reference

use file_io::{load_file_as_string, replace_str_in_file, save_string_to_file};
use std::path::Path;

// Path to file.
let path: &Path = Path::new("folder/subfolder_8/file_6.txt");

// Create a file with some content.
save_string_to_file("Hello, world!", path);

// Replace "Hello" with "Goodbye".
replace_str_in_file(path, "Hello", "Goodbye");

// Verify that the content was replaced.
let content = load_file_as_string(path);
assert_eq!(content, "Goodbye, world!");