How to replace a line in a text file?

How can I use fprintf to write a sentence/string in a text file on a specific line in the text file?

Respuestas (1)

dpb
dpb el 19 de Sept. de 2023

0 votos

text files are sequential files and can't easily be written to in the middle...in MATLAB, the simplest thing to do will be to read the existing file into memory (readlines will return a string array), make the necessary/wanted modifications in memory to that array and then rewrite the file (or make a new one) with writelines
Alternatively, you can process the file line by line with fgets, modify/pass thru each line in turn and rewrite with fwrite(*). If new line is to be inserted, the code needs to know what that is to be and at which line it should be inserted (or similarly, be able to know/skip rewriting any line(s) that aren't to be in the new file.
But, doing it in place in the existing file is just not the practical way to approach the problem.
(*) I've posted sample filter doing this at least once before but I don't have a link to it at hand; maybe a search for @fgetl and "filter" might find it...

3 comentarios

Ali Almakhmari
Ali Almakhmari el 19 de Sept. de 2023
I see. Let me give you more details about what I want to do perhaps you can help me better. So I have a text file with like 20000 lines. But starting from line 6826 and going by increments of 5, what I need to do is search for the string 2021 and change it to 2022, and then go to line 6831, do the same, and then go to 6836, and so on. I am just not sure how I can do this in MATLAB.
Voss
Voss el 19 de Sept. de 2023
Editada: Voss el 19 de Sept. de 2023
str = readlines(filename);
str(6826:5:end) = strrep(str(6826:5:end),"2021","2022");
writelines(str,filename);
dpb
dpb el 19 de Sept. de 2023
Editada: dpb el 19 de Sept. de 2023
If it just happens that the year number 2021 starts at line 6826 in the file and there are four lines between it and the next, but not a year number in those that would match, then you could generalize the string replacement to just replace 2021 with 2022.
str= strrep(str,"2021","2022");
would be the same under those conditions.
If there were other instances of "2021" that were NOT to be changed, then would need the additional logic, yes.
You might find pattern of value here to be able to write a specific search/replace expression that does only the specific instances wanted in more general terms than counting lines.

Iniciar sesión para comentar.

Categorías

Más información sobre Characters and Strings en Centro de ayuda y File Exchange.

Productos

Versión

R2022b

Etiquetas

Preguntada:

el 19 de Sept. de 2023

Editada:

dpb
el 19 de Sept. de 2023

Community Treasure Hunt

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

Start Hunting!

Translated by