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

2 visualizaciones (últimos 30 días)
Kazi Alam
Kazi Alam el 14 de Jul. de 2021
Comentada: Walter Roberson el 14 de Jul. de 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?

Respuestas (1)

Walter Roberson
Walter Roberson el 14 de Jul. de 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.
  2 comentarios
Kazi Alam
Kazi Alam el 14 de Jul. de 2021
@Walter Roberson Do you know the reason for the following error?
lines = readlines("zone.txt");
Unrecognized function or variable 'readlines'.
Walter Roberson
Walter Roberson el 14 de Jul. de 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.
See
https://www.mathworks.com/matlabcentral/answers/877228-best-solution-to-finding-repeating-characters-on-a-line#comment_1636553

Iniciar sesión para comentar.

Categorías

Más información sobre Low-Level File I/O en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by