0

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:

  • reads Parameters.m
  • searches for a line in it (e.g. dt=1)
  • replaces it with something else (e.g. dt=0.6)
  • saves Parameters.m.

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?

odnerpmocon
  • 282
  • 1
  • 4
  • 17

1 Answers1

1

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');
Suever
  • 64,497
  • 14
  • 82
  • 101
  • Thanks. Could you explain briefly what (contents, '(?<=\ndt=).*?(?<=\n)', '0.6') means? If I know for sure that dt=1 in my file (and it appears nowhere else in my file), can I replace it with (contents, 'dt=1', 'dt=0.6')? – odnerpmocon Feb 25 '17 at 04:53
  • @odnerpmocon It's a regular expression which matches any number that follows `dt=` and replaces it with `0.6`. It's more robust than searching for purely `dt=1` – Suever Feb 25 '17 at 04:55