Effacer les filtres
Effacer les filtres

Replace string in text file

88 vues (au cours des 30 derniers jours)
Kian
Kian le 12 Août 2020
I have a txt file in which there are a bunch of lines. The first two lines are shown below:
10125731872 50 3731 -9999 307 166 -9999 827 4090 -9999 587 332 5 -9999
10125731873 50 117 322 9 -9999 187 300 1273 280 103 -9999 39 -9999
I need to add an "M" after all -9999 values. In a text editor this would be simply done by using the replace tool while looking for all "-9999 " and replacing them with "-9999M". Simple! But I have a hard time doing the same thing in Matlab.
Any idea how I can do this simple task?
Thanks.

Réponse acceptée

Walter Roberson
Walter Roberson le 12 Août 2020
filename = 'a_txt_file.txt';
new_filename = ['new_' filename];
S = fileread(filename);
S = regexprep(S, '-9999\>', '$&M');
fid = fopen(new_filename, 'w');
fwrite(fid, S);
fclose(fid);
It is recommended that new_filename be different than filename: otherwise if something goes wrong in the writing process, you could lose your only copy of the input.
  5 commentaires
Walter Roberson
Walter Roberson le 12 Août 2020
Modifié(e) : Walter Roberson le 12 Août 2020
regexprep(S, '-9999( |$)', '-9999M', 'lineanchors' )
Kian
Kian le 12 Août 2020
Thanks a lot. This is really neat!

Connectez-vous pour commenter.

Plus de réponses (1)

kuchina mani chandra
kuchina mani chandra le 3 Avr 2023
Function replaceStringIntxtFile(filepath,stringToReplace,ReplaceWith) Filedata = readlines(filepath); replacedFiledata =replace(Filedata,stringToReplace,ReplaceWith); F=fopen(filepath,'w'); fprintf(f,'%s\n'replacedFiledata); fclose(f) end

Catégories

En savoir plus sur Characters and Strings 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