How to edit a number in a text file and save a copy of the file multiple times?
6 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Dear Members,
I need to do a probabilisitc analysis where I will be generating thousands of input text files, they all will be the same except the 2 numbers in the red circle below will change each time (the 2 numbers will be replaced by another 2 numbers from a vector). Can you please suggest a method for editing these 2 numbers in MATLAB and saving them in a new text file copy?
(You can find the text file attached)
Thank you!
![Capture1.PNG](https://www.mathworks.com/matlabcentral/answers/uploaded_files/213486/Capture1.png)
0 commentaires
Réponse acceptée
Stephen23
le 12 Avr 2019
Modifié(e) : Stephen23
le 12 Avr 2019
vec = [23,5]; % new values
cnt = 0;
rgx = '^(\s*\S+\s+)(\S+)(.+gamma.+)$';
f1d = fopen( 'input_matlab.txt','rt');
f2d = fopen('output_matlab.txt','wt');
while ~feof(f1d)
str = fgetl(f1d);
tkn = regexp(str,rgx,'once','tokens');
if ~isempty(tkn)
cnt = cnt+1;
str = sprintf('%s%#.14E%s',tkn{1},vec(cnt),tkn{3});
end
fprintf(f2d,'%s\n',str);
end
fclose(f1d);
fclose(f2d);
Repeat for each file:
4 commentaires
Stephen23
le 13 Avr 2019
Modifié(e) : Stephen23
le 13 Avr 2019
"But can you please elaborate what does this line mean?"
That line defines a regular expression. Regular expressions are a special language for parsing strings by matching specific substrings or character types. It matches:
rgx = '^(\s*\S+\s+)(\S+)(.+gamma.+)$';
% ^ start of the string.
% ( start of token 1.
% \s* zero or more whitespace characters.
% \S+ one or more non-whitespace chars.
% \s+ one or more whitespace char.
% ) end of token 1.
% ( start of token 2.
% \S+ one or more non-whitespace char (i.e. the number you want)
% ) end of token 2.
% ( start of token 3.
% .+ one or more char.
% gamma the word "gamma"
% .+ one or more char.
% ) end of token 3.
% $ end of the string.
The word "gamma" only occurs on the lines that you want to match. The second token matches the number that you want to change. The first and third tokens match everything else on the line, before and after that number. The code simply replaces the second token, everything else from the file remains exactly the same.
You can learn about regular expressions here:
"Also the process should be automated for thousands of txt files"
Read the link that I gave you. Use sprintf to generate the file names, and change the name used in fopen (for the output file!)
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Data Import and Export dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!