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

110 次查看(过去 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.
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 CenterFile Exchange 中查找有关 Text Data Preparation 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by