Edit line in text document

2 vues (au cours des 30 derniers jours)
Christoph
Christoph le 10 Avr 2013
Is there a way to change one line in a text document? My impression is that with fopen and fprintf there is no way to just edit the contents a line, leaving the rest of the doc unchanged. I tried the following:
fid = fopen(doc,'r+);
while true
str = fgetl(fid);
if feof(fid) % break out of loop and end of doc
break
end
if strcmp(str,checkstr)
newstr = [str 'abc'];
fprintf(fid,'%s',newstr);
end
end
fclose(fid);
But I cannot get this to work (if I run the code, the document is not changed). I tried to play with additional tags like \r or \n, but I couldn't get it to work. Is there something I am missing, or is it generally not possible (with reasonable effort) to just edit a text file, in which case I guess I will have to create a copy of the full file?

Réponse acceptée

Cedric
Cedric le 10 Avr 2013
If you want to change part of a line based on a match (checkstr), a good way to achieve this is to use regular expressions, e.g.
buffer = fileread('inFile.txt') ;
buffer = regexprep(buffer, 'I hate regexp', 'I love regexp') ;
fid = fopen('outFile.txt', 'w') ;
fwrite(fid, buffer) ;
fclose(fid) ;
If you tell me the pattern that you are matching and the replacement, I can help you building a pattern for the regexp if it is more elaborate that basic alpha-numeric characters.
  1 commentaire
Christoph
Christoph le 11 Avr 2013
Great, thanks so much, this is exactly what I was looking for! I already tried it and it works perfectly fine! The regular expressions are easy to handle in my case, because what I want to do is edit the html file generated by the Matlab publisher, and thanks to all the tags in there I can locate the places I want to edit easily enough.
Thanks also for the other answer! It achieves the same desired result, but I prefer this solution because I feel it's simpler (I don't have to loop line by line) and I can use it for editing the original document, without creating a temp file.

Connectez-vous pour commenter.

Plus de réponses (1)

PT
PT le 10 Avr 2013
Two issues:
1. As the help of fopen states, you must have a fseek between fgetl and fprintf.
2. You are changing the overall file size by inserting. It might be better if you save to a temp file and replace the original file with the temp file at the end of your operation.
%{
File content:
good
morning
to you
%}
checkstr = 'morning';
fin = fopen('test.txt','r');
fout = fopen('testout.txt','w');
while ~feof(fin);
str = fgetl(fin);
if strcmp(str,checkstr)
str = [str 'abc'];
end
fprintf(fout, '%s\n', str);
end
fclose(fin);
fclose(fout);

Catégories

En savoir plus sur Environment and Settings dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by