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

2 ビュー (過去 30 日間)
Kazi Alam
Kazi Alam 2021 年 7 月 14 日
コメント済み: Walter Roberson 2021 年 7 月 14 日
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 Center および File ExchangeLow-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