MATLAB: How to change a specific line in a text file

linetext filetext;

Hi
I have a text file, where different forms of content exist, data or strings or symbols, i need to change a specific line (it's only a number), i know its position (69 line)
Is there any way to do so?

Best Answer

  1. Loading txt into a cell.
  2. Then do whatever you want with the cell. In this example, line 69 will be 99.
  3. Then write the cell into a txt.
% Read txt into cell A
fid = fopen('test.txt','r');
i = 1;
tline = fgetl(fid);
A{i} = tline;
while ischar(tline)
i = i+1;
tline = fgetl(fid);
A{i} = tline;
end
fclose(fid);
% Change cell A
A{69} = sprintf('%d',99);
% Write cell A into txt
fid = fopen('test2.txt', 'w');
for i = 1:numel(A)
if A{i+1} == -1
fprintf(fid,'%s', A{i});
break
else
fprintf(fid,'%s\n', A{i});
end
end