How can i replace a line form a text ?

조회 수: 4 (최근 30일)
Theodor Al Saify
Theodor Al Saify 2018년 8월 21일
댓글: Theodor Al Saify 2018년 8월 21일
I have the following text file i want to replace all the line that contains this pattern X = 259.557 mm, Y = 563.173 mm, Z = -104.284 mm,
with a new line that contains the existing numbers added by a certain value.

채택된 답변

Stephen23
Stephen23 2018년 8월 21일
편집: Stephen23 2018년 8월 21일
You can easily match those lines using a regular expression. Something like this:
fmt = sprintf('\\s*%c\\s*=\\s*(\\d+\\.\\d+)\\s*mm,','XYZ')
fmt = sprintf('^%s\\s*$',fmt)
str = fileread('values.txt');
spl = regexp(str,'[\n\r]+','split');
tmp = regexp(spl,fmt,'tokens','once');
idx = find(~cellfun('isempty',tmp));
for k = reshape(idx,1,[])
vec = str2double(tmp{k}) + 2; % add two as example data manipulation.
spl{k} = sprintf(' X = %.3f, Y = %.3f, Z = %.3f,',vec);
end
fid = fopen('newfile.txt','wt');
fprintf(fid,'%s\n',spl{:});
fclose(fid);
  댓글 수: 5
Stephen23
Stephen23 2018년 8월 21일
편집: Stephen23 2018년 8월 21일
Change the first line to this:
fmt = sprintf('\\s*%c\\s*=\\s*([-+]?\\d+\\.\\d+)\\s*mm,','XYZ')
^^^^^ optional +/- sign
Theodor Al Saify
Theodor Al Saify 2018년 8월 21일
Thank you it work perfectly . :D

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

추가 답변 (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