Is it possible to insert or replace text in the middle of an ASCII file in MATLAB 8.1 (R2013a)?

6 views (last 30 days)
I have an ASCII file I am reading in line-by-line into MATLAB. When I find a particular line, I want to replace it. FOPEN only allows me to open a file for either overwriting or appending. Neither of these would allow me to replace text in the middle of the file.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 16 Jul 2013
The ability to replace lines in the middle of an ASCII file is not available in MATLAB 8.1 (R2013a)?
To work around this issue, you can write a new file as you are reading in the original file line-by-line. When you reach the line you would like to change, write the new line to the new file. Then continue to copy the rest of the original file line-by-line to the new file.
An example of this approach that uses regular expressions to identify lines for replacement follows:
% open file for reading
fidr = fopen('TSr.txt','r') ;
% open file for writing
fidw = fopen('TSw.txt','w') ;
% while end of file has not been reached
while ( ~feof(fidr) )
% read line from reading file
str = fgets(fidr) ;
% match line to regular expression to determine if replacement needed
match = regexp(str,'(?<=Line )\d(?= is this.)', 'match' ) ;
% if line is to be replaced
if ( ~isempty(match) )
% define replacement line
str = ['This is line ',match{1},'.',char(10)] ;
end
% write line to writing file
fwrite(fidw,str) ;
end
where the 'TSr.txt' file that is read is
This is line 1.
This is line 2.
Line 3 is this.
Line 4 is this.
This is line 5.
and the 'TSw.txt' file that is written is
This is line 1.
This is line 2.
This is line 3.
This is line 4.
This is line 5.

More Answers (0)

Categories

Find more on Scope Variables and Generate Names in Help Center and File Exchange

Products


Release

R2013a

Community Treasure Hunt

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

Start Hunting!