First, you should open the file and read it into a String
(assuming the file is entirely ASCII or UTF-8 text). The convenience function read_to_string()
is probably easiest for this, but you can use the functions under OpenOptions
and File
to open and read the file manually instead for future reference. Then you should use the methods on String
to edit the returned String
. The methods match_indicies()
(which produces an iterator over all the indices where there is a match against a particular pattern) and replace_range()
may be particularly useful for finding and replacing the relevant portions of the String
. If the replacement text is the same in each case replace()
may be a more efficient approach. For this sort of use-case you may also consider a regular expression library like regex
. Then you just need to write the text back to the file with something like write()
.
1 Like