Replace repeated pattern in text file
조회 수: 3 (최근 30일)
이전 댓글 표시
Hi guys,
I have a .txt file where the string param is present in the form param1, param2,param3,....
What I would like to do is replace each of this param pattern with a different value. let's say if I have param1, param2 and param3 I want to replace these with three different values contained in a vector. I have tried with the following code: %%%%%%%%%%%%%
fin = fopen(['a.op4'],'r'); fout = fopen(['b.op4'],'wt');
for j = 10:16
while ~feof(fin)
s = fgetl(fin);
s = strrep(s,['param',num2str(j)],num2str(values(j)));
fprintf(fout,'%s\n',s);
end
%%%%%%%%%%%%%%%%
But in this way it only replaces the value at param10 (first vakue of j). Any idea why?
Thanks!
댓글 수: 0
채택된 답변
Guillaume
2017년 7월 17일
편집: Guillaume
2017년 7월 17일
You're trying to loop over two different things at once. Much simpler:
filepath = 'c:\somewhere\somefile.extension';
filecontent = fileread(filepath); %read the whole file at once rather than line by line
for paramvalue = 10:16
filecontent = strrep(filecontent, ['param',num2str(paramvalue)], num2str(values(paramvalue))); %replace each parameter
end
%write the file back:
fid = fopen(filepath, 'w');
fwrite(filecontent);
fclose(fid);
filepath = 'c:\somewhere\somefile.extension';
filecontent = fileread(filepath);
%replace param10 - param16 at once with values(10)- values(16):
filecontent = regexprep(filecontent, 'param(1[0-6])', '${num2str(values(str2double($1)))}');
%... save file
댓글 수: 4
Guillaume
2017년 7월 17일
편집: Guillaume
2017년 7월 17일
If you want the replacement string to be padded with spaces to be the same length as the original you can use, assuming that values is all integers:
filecontent = regexprep(filecontent, 'param(1[0-6])', '${sprintf(sprintf(''%%%dd'', numel($0)), values(str2double($1)))}')
Quite a mouthful of a replacement expression! Or since, the length of 'paramxx' is always the same, you could use the simpler:
filecontent = regexprep(filecontent, 'param(1[0-6])', '${sprintf(''% 7d'', values(str2double($1)))}')
Adjust the sprintf format string as appropriate if values are not integer. You can had a format string the same way for the strrep option if you wish.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Environment and Settings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!