MATLAB: Replacing a string with another string in a text file

MATLABtext filetextprocessingtextscan

My file reads something like this:
"name of unique string"
x= 10, 1, 0, 1, 10
y= 500, 50, 0, 50 500
Now I know how to locate the "name of unique string" BUT what I want to replace is the "y= 500,50,0,50,500".
Can someone help me out with this please?
Thanks in advance, Aniruddh

Best Answer

The thing about sequential files is that they're, well..."sequential"
You've got a couple of choices -- read the full file as character data and operate in memory to change the 3rd record (determined either by knowing it is the nth record or a search) and then writing the modified memory to a new (or overwrite the existing) file. NB: make backups while testing the latter!!!
Alternatively and for short files probably the easier is to read the file a line at a time, ( fgetl is your friend here) and echoing that line back to a new file until you find the line in question at which time you make the desired change and write the modified record. Then, of course, complete to feof on the file.
fidi=fopen('inputfile','r');
fido=fopen('outputfile','w');
while ~feof(fidi)
l=fgetl(fidi); % read line
if strfind(l,'y=')
% modify line here
l='whatever new string';
end
fprintf(fido,'%s',l) % 'fgetl returns \n so it's embedded
end
fidi=fclose(fidi);
fido=fclose(fido);
Salt to suit...