MATLAB Answers


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?



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');

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{:});

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


Join the 15-year community celebration.

Play games and win prizes!

Learn more
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

MATLAB Academy

New to MATLAB?

Learn MATLAB today!