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

2 ビュー (過去 30 日間)
Charles Cummings
Charles Cummings 2019 年 1 月 22 日
コメント済み: Charles Cummings 2019 年 1 月 23 日
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 Center および File ExchangeData Import and Export についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by