how to modify a text file replacing an existing string with an user-defined string

128 ビュー (過去 30 日間)
Hello,
I want to open an existing text file, modify it adding a string that I define and save the new file. The new string shall replace a string on the existing file, so I must identify it.
Any help appreciated, regards, Hugo

採用された回答

Jos (10584)
Jos (10584) 2013 年 12 月 11 日
fid = fopen('infile.txt','rt') ;
X = fread(fid) ;
fclose(fid) ;
X = char(X.') ;
% replace string S1 with string S2
Y = strrep(X, S1, S2) ;
fid2 = fopen('outfile.txt','wt') ;
fwrite(fid2,Y) ;
fclose (fid2) ;

その他の回答 (2 件)

Walter Roberson
Walter Roberson 2013 年 3 月 13 日
You cannot do this unless the replacement string is exactly the same length as the original string. Even then it is not recommended. Instead, create an output file, copy everything from the input until you reach the place you want to modify, write the new string without copying the old string, and then copy the rest of the old file to the new one. You can rename the new file to the old name if you need to afterwards.
  2 件のコメント
Hugo
Hugo 2013 年 3 月 13 日
How can I do: -create an output file -copy everything from the input until you reach the place you want to modify -write the new string without copying the old string -copy the rest of the old file to the new one. -Rename the new file to the old name if you need to afterwards
Can you please tell me what commands shall I use for each one of this steps?
thanks for replying, Hugo

サインインしてコメントする。


Andreas Justin
Andreas Justin 2013 年 12 月 11 日
編集済み: Andreas Justin 2013 年 12 月 11 日
Something like this?
%%Preparing
fid = fopen(fullfile('D:\','test.txt'),'w');
fprintf(fid,['function edit(str)',char(13), 'if nargin < 1 || isempty(str)',char(13),...
'str='''';',char(13),'end',char(13), 'rmpath(matlabroot);',char(13),...
'edit(str);',char(13), 'addpath(matlabroot);',char(13),'Matlab_extendEditorFunctionality(true);']);
fclose(fid);
clear fid
%%Reading
fid = fopen('D:\test.txt','r');
f = textscan(fid,'%s','Delimiter','\n');
txt = f{:};
%%manipulation
txt = regexprep(txt,'^function','\<FUNCTION\>')
txt = regexprep(txt,'path','\<PATH\>')
txt = regexprep(txt,'(.*)','$1\n');
txt = [txt{:}];
fclose(fid);
%%writing
fid = fopen('D:\test.txt','w');
fprintf(fid,txt)
fclose(fid);
  1 件のコメント
Marco A. Acevedo Z.
Marco A. Acevedo Z. 2022 年 2 月 17 日
Hello, this solution misses the tabulation spaces. That might be inconvenient for doing search and replace of XML files. On those specific cases use:
new_filename = ['new_' str2];
S = fileread(str2);
S = regexprep(S, 'µm', 'micron');
fid = fopen(new_filename, 'w');
fwrite(fid, S);
fclose(fid);
Cheers,

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeText Data Preparation についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by