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

3 次查看(过去 30 天)
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!

回答(1 个)

Walter Roberson
Walter Roberson 2019-1-22
S = fileread('changes.txt');
newS = regexprep(S, 'command.*$', 'command NEWVALUE', 'dotexceptnewline', 'lineanchors');
fid = fopen('new_changes.txt', 'wt');
fwrite(fid, newS);
fclose(fid);
  1 个评论
Charles Cummings
Charles Cummings 2019-1-23
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Data Import and Export 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by