Replace repeated pattern in text file
3 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Guillaume
on 17 Jul 2017
Edited: Guillaume
on 17 Jul 2017
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 Comments
Guillaume
on 17 Jul 2017
Edited: Guillaume
on 17 Jul 2017
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.
More Answers (0)
See Also
Categories
Find more on Environment and Settings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!