MATLAB Answers

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

2 views (last 30 days)
Kazi Alam
Kazi Alam on 14 Jul 2021
Commented: Walter Roberson on 14 Jul 2021
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?

Answers (1)

Walter Roberson
Walter Roberson on 14 Jul 2021
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.
Walter Roberson
Walter Roberson on 14 Jul 2021
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.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by