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

112 vues (au cours des 30 derniers jours)
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

Réponse acceptée

Jos (10584)
Jos (10584) le 11 Déc 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) ;

Plus de réponses (2)

Walter Roberson
Walter Roberson le 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 commentaires
Hugo
Hugo le 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

Connectez-vous pour commenter.


Andreas Justin
Andreas Justin le 11 Déc 2013
Modifié(e) : Andreas Justin le 11 Déc 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 commentaire
Marco A. Acevedo Z.
Marco A. Acevedo Z. le 17 Fév 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,

Connectez-vous pour commenter.

Catégories

En savoir plus sur Text Data Preparation dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by