How to overwrite the existing data inside the same file.

24 vues (au cours des 30 derniers jours)
Muharrem Askin
Muharrem Askin le 25 Juin 2012
I have file consisting of many lines. I would like to search and change some of the lines without writing it to a new file . For example,my data goes like this and I would like to increase IDLEPITCH one by one in each iteration and I would like to replace 90 with 91-92-93 .. inside the same file. Is it possible to do this ? otherwise I need to create a new file each time and it will be many files in the end. STALLH Y IDLEPITCH 90 WDIR 0 DFLAP 0.007 DEDGE 0.008

Réponses (2)

TAB
TAB le 25 Juin 2012
f=fopen('YourFile.txt','r');
FData = textscan(f,'%s');
fclose(f);
idx=find(strcmp(FData{1},'IDLEPITCH')==1);
FData{1}{idx+1}='91';
f=fopen('YourFile.txt','w');
for x=1:length(FData{1})
fprintf(f,'%s ',FData{1}{x});
end
fclose(f);

Walter Roberson
Walter Roberson le 25 Juin 2012
Unless you will always be replacing text with exactly the same number of characters (e.g., the 90 will never go as high as 100 in the file), then replacing text is tricky. The best way to do it properly is not to do it -- that is, to write out a new file instead. You can delete the old file and rename the new file to the old one after you make the change so that you do not have files accumulating.

Catégories

En savoir plus sur Data Type Conversion 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