Read and replace text in a file, save as .m

3 views (last 30 days)
I have a .prm file i am trying to manipulate the values of within a script I created. I am able to find the specific line the text i am trying to change using
st = fopen('changes.txt','r') % i changed the file type to a .txt file and placed it in the same location
fgetl(st) %have to use this command 7 times before I find the right line.
But that is as far as I've gotten that seems to be right. the file is of the format
command argument
where I am attempting to change the numerical value used in argument.
Have attempted using a number of functions to load the data and fopen was the only one that seemed to get anywhere
Thanks!

Answers (1)

Walter Roberson
Walter Roberson on 22 Jan 2019
S = fileread('changes.txt');
newS = regexprep(S, 'command.*$', 'command NEWVALUE', 'dotexceptnewline', 'lineanchors');
fid = fopen('new_changes.txt', 'wt');
fwrite(fid, newS);
fclose(fid);
  1 Comment
Charles Cummings
Charles Cummings on 23 Jan 2019
Is it possible to loop through the newvalue?
S = fileread('changes.txt');
newvalue=0
for newvalue<10000
newvalue=newvalue+500
newS = regexprep(S, 'command.*$', 'newvalue', 'dotexceptnewline', 'lineanchors');
fid = fopen('new_changes.txt', 'wt');
fwrite(fid, newS);
fclose(fid);
end
Obviously wouldnt be that simple.

Sign in to comment.

Categories

Find more on Data Import and Export in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!