Replace repeated pattern in text file

3 visualizaciones (últimos 30 días)
salvor
salvor el 17 de Jul. de 2017
Editada: Guillaume el 17 de Jul. de 2017
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!

Respuesta aceptada

Guillaume
Guillaume el 17 de Jul. de 2017
Editada: Guillaume el 17 de Jul. de 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);
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 comentarios
salvor
salvor el 17 de Jul. de 2017
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 el 17 de Jul. de 2017
Editada: Guillaume el 17 de Jul. de 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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Environment and Settings en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by