Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

To resolve issues starting MATLAB on Mac OS X 10.10 (Yosemite) visit: http://www.mathworks.com/matlabcentral/answers/159016

Replacing and Inserting a text in an ASCII file

Asked by AP on 5 Jun 2011

How can I insert a text with multiple lines and also replace a text in an ASCII file?

0 Comments

AP

Products

No products are associated with this question.

2 Answers

Answer by Jan Simon on 6 Jun 2011

You can read the file into a string or cell string, perform the operations and write it back again:

Replace in string method:

Str = fileread(FileName);
Str2 = strrep(Str, 'toReplace', 'Replacement');
FID = fopen(FileName, 'w');
if FID < 0, error('Cannot open file'); end
fwrite(FID, Str2, 'uchar');
fclose(FID);

To insert lines in addition:

CStr = regexp(fileread(FileName), char(10), 'split');
CStr2 = strrep(CStr, 'toReplace', 'Replacement');
CStr2 = cat(2, CStr2(1:10), {'Inserted line'}, CStr2(11:end));
FID = fopen(FileName, 'w');
if FID < 0, error('Cannot open file'); end
fprintf(FID, '%s\n', CStr2{:});
fclose(FID);

Care for modern CHAR(10) or DOS style CHAR([13, 10]) linebreaks on demand.

0 Comments

Jan Simon

Contact us