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:
fidr = fopen('TSr.txt','r') ;
fidw = fopen('TSw.txt','w') ;
while ( ~feof(fidr) )
str = fgets(fidr) ;
match = regexp(str,'(?<=Line )\d(?= is this.)', 'match' ) ;
if ( ~isempty(match) )
str = ['This is line ',match{1},'.',char(10)] ;
end
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.
Best Answer