How to replace numbers on a particular line from text file?

4 次查看(过去 30 天)
Hallo, Thanks for reading!
As an example, I have the following text file (the line number does not exist on the real text file).
1 ((SUBWALL :N "Part 1" :T WALL-PART :D "Wall part_C")
2 (:PAR :N X :V 0.0)
3 (:PAR :N DX :V 1)
4 (:PAR :N DY :V 1)
5 ((SUBWALL :N "Part 1" :T WALL-PART :D "Wall part_WN")
6 (:PAR :N X :V 0.0)
7 (:PAR :N DX :V 0.5)
8 (:PAR :N DY :V 0.5)
I want to replace the '0.0' from line 2 with '2.1'. The code I used as follows.
x = 2.1;
r_line = '(:PAR :N X :V %.1f)';
r_bb = sprintf(r_line,x);
However, it is replacing both line 2 and 6. How can avoid this and only change the digits in line 2?

回答(1 个)

Walter Roberson
Walter Roberson 2021-7-14
Use readlines() to read the text file and split into lines. Then index the cell array to make changes.
After fopen a new file and fprintf(fid, '%s\n', TheCell{:}) and fclose.
  2 个评论
Kazi Alam
Kazi Alam 2021-7-14
@Walter Roberson Do you know the reason for the following error?
lines = readlines("zone.txt");
Unrecognized function or variable 'readlines'.
Walter Roberson
Walter Roberson 2021-7-14
Hmmmm... you could have a corrupt MATLAB.
Or... you could be using an old version of MATLAB and forgot to mention that and didn't think that it was important to fill out the Release field when doing so helps avoid exactly these kind of difficulties.
See
https://www.mathworks.com/matlabcentral/answers/877228-best-solution-to-finding-repeating-characters-on-a-line#comment_1636553

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Low-Level File I/O 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by