Replace repeated pattern in text file

조회 수: 3 (최근 30일)
salvor
salvor 2017년 7월 17일
편집: Guillaume 2017년 7월 17일
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!

채택된 답변

Guillaume
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);
You could also completely eliminate the loops by using a dynamic regular expression:
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
salvor
salvor 2017년 7월 17일
It works. The only issue is that the syntax of the file is slightly changed. So when param is replaced, the new number is not aligned with the others in the column
Guillaume
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 CenterFile Exchange에서 Environment and Settings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by