How to replace multiple strings in a txt file

조회 수: 9 (최근 30일)
steven grob
steven grob 2012년 9월 6일
Hi,
I would like to couple matlab to a another program so I can make a lot of models in a fast way. To do so, I need a txt file with commands in which I can modify some strings with Matlab. For example, in the txt file the commands are written...
*add_points
3
0
x1
0
0
x2
5
0
3
5
0
*set_curve_type line
*add_curves
50
49
49
52
52
51
*set_curve_type fillet
*add_curves
23
24
x3
..... and the idea is to replace x1,x2 and x3 with the values from A in which A is a 10*3 matrix and x1=A(1,:) and x2=(2,:) and x3=A(3,:).
So I have 10 text files to make the 10 models.
My question is: how to do this? I tried to use commands as txtscan, strrep but that didn't work for me...
Any suggestions? What would be the most easy way?
Thanks in advance!
Steven

채택된 답변

Sven
Sven 2012년 9월 7일
편집: Sven 2012년 9월 7일
Hi Steven,
Try this, it's basically 3 steps:
  1. Read the file into a cell of strings (1 per line in the original file)
  2. Replace the keywords via a regexprep
  3. Save the new file
Does it work for you?
linesCell = cell(10000,1);
fid=fopen('myFile.txt');
lineNo = 0;
while 1
lineNo = lineNo+1;
linesCell{lineNo} = fgetl(fid);
if ~ischar(linesCell{lineNo}), break, end
end
fclose(fid);
linesCell(lineNo:end) = [];
A = rand(3,1);
for i = 1:size(A,1)
linesCell = regexprep(linesCell,sprintf('x%d',i),sprintf('%f',A(i)));
end
fid=fopen('myFileOut.txt','wt');
fprintf('%s\n',linesCell{:});
fclose(fid)
  댓글 수: 2
steven grob
steven grob 2012년 9월 7일
I added fid in
fprintf(fid,'%s\n',linesCell{:});
but it works perfect now!
Thanks Sven
Sven
Sven 2012년 9월 7일
Ah, yep - typo, but you got it. Glad it helped.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by