How to edit a number in a text file and save a copy of the file multiple times?
조회 수: 6 (최근 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](https://www.mathworks.com/matlabcentral/answers/uploaded_files/213486/Capture1.png)
댓글 수: 0
채택된 답변
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
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 Center 및 File Exchange에서 Data Import and Export에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!