I have two files, Editor.m and Parameters.m. I want to write a code in Editor.m that when run does the following task:
So, at the end of this process, Parameters.m will contain the line dt=0.6 instead of dt=1, without me having edited it directly.
Is there a way to do this? If so, how?
You can use regexprep
to replace the value of interest.
% Read the file contents
fid = fopen('Parameters.m', 'r');
contents = fread(fid, '*char').';
fclose(fid);
% Replace the necessary values
contents = regexprep(contents, '(?<=dt=)\d*\.?\d+', '0.6');
% Save the new string back to the file
fid = fopen('Parameters.m', 'w');
fwrite(fid, contents)
fclose(fid)
If you can guarantee that it will only ever appear as 'dt=1'
, then you can use strrep
instead
contents = strrep(contents, 'dt=1', 'dt=0.6');