Replace repeated pattern in text file

2 次查看(过去 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!

采纳的回答

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 中查找有关 String Parsing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by