How to edit a number in a text file and save a copy of the file multiple times?

4 次查看(过去 30 天)
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

采纳的回答

Stephen23
Stephen23 2019-4-12
编辑:Stephen23 2019-4-12
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 个评论
Stephen23
Stephen23 2019-4-13
编辑:Stephen23 2019-4-13
"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!)

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Language Support 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by