필터 지우기
필터 지우기

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

조회 수: 4 (최근 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 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