How can i replace a line form a text ?

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 日

0 投票

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 件のコメント

Theodor Al Saify
Theodor Al Saify 2018 年 8 月 21 日
nothing has changed when i run the code , Do i need to modify anything in it ?
Stephen23
Stephen23 2018 年 8 月 21 日
編集済み: Stephen23 2018 年 8 月 21 日
It creates a new file called 'newfile.txt' Check that file and you will see that each X,Y,Z value has increased by two, as the comment describes.
You could overwrite the original file, but I would not recommend doing this until the code has been well tested.
Theodor Al Saify
Theodor Al Saify 2018 年 8 月 21 日
I found that the problem is for the (-) sign sometimes the numbers are negative and won't match the pattern. Do you know how i can fix it ?
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 件)

カテゴリ

ヘルプ センター および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by