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

조회 수: 92 (최근 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 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