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

110 views (last 30 days)
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

Accepted Answer

Jos (10584)
Jos (10584) on 11 Dec 2013
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) ;

More Answers (2)

Walter Roberson
Walter Roberson on 13 Mar 2013
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 Comments
Hugo
Hugo on 13 Mar 2013
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

Sign in to comment.


Andreas Justin
Andreas Justin on 11 Dec 2013
Edited: Andreas Justin on 11 Dec 2013
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 Comment
Marco A. Acevedo Z.
Marco A. Acevedo Z. on 17 Feb 2022
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,

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!