remove and replace text in a .dat file

11 Ansichten (letzte 30 Tage)
Joshua Ford
Joshua Ford am 17 Okt. 2022
Kommentiert: Jan am 18 Okt. 2022
Hi,
I am trying to find a certain line within a .dat file and replace its contents and save it back to the orignal place within matlab. I have been able to find the character position of the text i wish to replace but do not know how to overwrite a specific location of a .dat file.
I have used fileread to read the file as characters and then replace it but cannot find a way to then save that as a .dat file. Any method will be good thank you. I essentially want to replace a lince of text which is a filepath name (assume you dont konw the lenght or contents of the filepath) with a stated filepath

Akzeptierte Antwort

Jan
Jan am 17 Okt. 2022
Bearbeitet: Jan am 17 Okt. 2022
You cannot replace a line in a text file on the disk directly, because the new text might have another number of characters than the old one.
FileName = 'C:\Your\file.dat';
C = fileread(FileName);
C = strrep(C, oldText, newText);
% Modern Matlab versions (since R2022a):
writelines(C, FileName);
% Old Matlab versions:
[fid, msg] = fopen(FileName, 'w');
assert(fid > 0, msg);
fwrite(fid, C, 'char');
fclose(fid);
  2 Kommentare
Joshua Ford
Joshua Ford am 18 Okt. 2022
Hi thanks for this. It worked really well.
I have a similar instance where I want to change a numerical value within a text file automatically. For instance the structure is:
100 Number
and I want to change it to
10 Number
How would I do this? I want to search for the word Number in the text file and then go back along the line to change the number?
Jan
Jan am 18 Okt. 2022
If your are 100 percent sure, that such a case cannot happen:
100 Number % original line
100000000000 Number % new line
you could overwrite the part without writing the complete file. But if the file is small, this is easier:
FileName = 'C:\Your\file.dat';
C = readlines(FileName);
m = contains(C, 'Number');
C(m) = sprintf("%-10d Number", 100);
writelines(C, FileName);

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Adding custom doc finden Sie in Help Center und File Exchange

Produkte


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by