MATLAB: Change a number that is followed by some text in a text file.

text file

Hi all,
I am fairly new to MATLAB, especially when it comes to doing text file manipulation.
I have a file that may look like this:
UNIT 1
5 ! Text1
7 ! Text2
0.0 ! Text3
45 ! Text4
UNIT 2
5 ! Text1
7 ! Text2
0.0 ! Text3
45 ! Text4
and so on… There is stuff before and after as well. I'm trying to change the numbers associated with, let's say, Text1, in UNIT1, but not UNIT2.
Any help would be greatly appreciated. Even just a push in the right direction.

Best Answer

First use fopen(), fgetl(), and fclose() to read the lines out of the file in a loop. Then use strfind to find the exclamation points then extracting the number, like this (untested):
baseFileName = 'data.txt';
fullFileName = fullfile(theFolder, baseFileName);
if exist(fullFileName, 'file')
fid = fopen(fullFileName);
tline = fgets(fid);
while ischar(tline)
%tline = '7 ! Text2'; for debugging.
disp(tline)
loc = strfind(tline , '!')
theNumber = str2double(tline (1:loc-1))
theIntegerNumber = int32(str2double(tline (1:loc-1)))
% Get next line.
tline = fgets(fid);
end
fclose(fid);
else
warningMessage = sprintf(File '%s not found', fullFileName );
uiwait(warndlg(warningMessage ));
end