MATLAB: How to read, change and write data back into the same txt file, at the same place

edit text fileMATLABread text filewrite text file

I have many files in one folder like the two examples attached. I want to change the number formed in columns 14-21 of any row that starts with "SO" "R " "TS" or "SH" by "2.335". Then write the numbers back to the row in the same file. Below is what I've tried so far:
clear; clc; close all;
delta = 2.335;% delta is the change in elevation
lst = dir('*.txt');
for n = 1:size(lst,1)
t = lst(1).name;
fid = fopen(t);
tline = fgets(fid);
while ischar(tline)
tline = fgetl(fid);
if tline(1) == 'S'& tline(2)== 'O'
disp(tline(15:21));
elev = str2num(tline(15:21));
elev = elev + delta;
elev = num2str(elev)
end
end
end
Thank you.

Best Answer

To replace a specific bit of text in a text file, you're going to have to rewrite the entire file. Assuming the files above are representative of your real files, this shouldn't be too time-consuming, because the files are small and easily fit in memory. So I recommend just reading in the entire file at once rather than looping over lines. Using either startsWith (in newer versions of Matlab) or strncmp (in older ones) will be a bit more efficient than your method of comparing individual characters.
The other key to replacing the text with your newly-calculated number is to make sure the new value has the same number of characters as the old one; you can make sure of that by using sprintf instead of num2str when converting your new value into a string.
% Read entire file as character array
txt = fileread(file);
% Split into lines
txt = regexp(txt, '\r\n', 'split');
% Find lines starting with certain letters
istarget = startsWith(txt, 'SO') | ...
startsWith(txt, 'R') | ...
startsWith(txt, 'TS') | ...
startsWith(txt, 'SH');
% Replace value in columns 15-21 with new value, properly formatted
delta = 2.335;
for ii = find(istarget)
elev = str2num(txt{ii}(15:21));
txt{ii}(15:21) = sprintf('%7.3f', elev+delta);
end
% Write to new file
fid = fopen('newfile.txt', 'wt');
fprintf(fid, '%s\n', txt{:});
fclose(fid);