MATLAB: How to make a small change to a big text file efficiently

text file small change huge file

Hi, I have a big normal text file, 5000 lines, where different forms of content exist, data or strings or symbols. And I want to change the data in only two locations.
e.g. data file content:
line 1-1000th ……
line 1001th ABCD
line 1002th 3 5 7
line till 5000th ……
What I know is that first to read the file line by line:
tline = fgetl(fid); data01{i} = tline;
find the line location after "ABCD", replace it with my new data:
data01{1002} = [9 0 0]; then write data01 line by line into the new file.
However, this takes too long time, due to the burden of reading each line. and I have a lot of files to work with.
Is there any faster way to do this? Any comment or hint will be appreciated! Thank you!
/Pengfei

Best Answer

Hi, this following code works fine, which strangely didn't take that long time as first try.
fin = fopen('inp.txt','r');
fout = fopen('out.txt','w');
idk=0;
while ~feof(fin)
idk=idk+1;
s = fgetl(fin);
if idk==250
s = num2str(5);
end
if idk==262
s = num2str(6);
end
if idk==1373
s = num2str([1 1 1]);
end
if idk==1380
s = num2str([8 8 8]);
end
fprintf(fout,'%s\n',s);
end
fclose(fin);
fclose(fout);