Borrar filtros
Borrar filtros

How to delete all lines in a text file after a certain word matches

9 visualizaciones (últimos 30 días)
What I need to do is to delete all lines (all the way to the end of the file) after some "keyword" and then add whatever lines I need, essentially "replacing" those last lines of a file with new lines. Attached is an example of the file I am dealing with.
Keyword in example file attached : 'KEY' <--- this is a variable!
Text to be replace after deleting all lines after KEY: 'LINES DELETION COMPLETE!' <--- this is a variable!
note: all lines with "blah" are what I want to delete, but they could be anything, I just want to delete all lines after KEY and replace them with specific text, using fprintf for example.
Any help would be much appreciated!

Respuesta aceptada

Walter Roberson
Walter Roberson el 7 de Sept. de 2022
Editada: Walter Roberson el 7 de Sept. de 2022
keyword = 'KEY';
newtext = "LINES DELETED" + newline + "Yes indeed, deleted" + newline;
%this part has to do with fetching your file over the network for the
%purposes of running the code with MATLAB Answers
filename = 'https://www.mathworks.com/matlabcentral/answers/uploaded_files/1119660/example.txt';
newfilename = 'example_out.txt';
tempfilename = tempname();
tempoutname = websave(tempfilename, filename);
%this is the important part for your purposes -- you would be using
%fileread() directly from your local file system instead of fetching over
%the network
S = fileread(tempoutname);
%do the substitution work
newS = regexprep(S, "^(?<=" + keyword + "\s*).*$", newtext, 'lineanchors');
%write result to a new file
fid = fopen(newfilename, 'w');
fwrite(fid, newS);
fclose(fid);
%cross-checking the results
dbtype(newfilename)
1 . 2 . 3 . 4 . 5 . 6 1 2 3 4 7 5 6 7 8 9 8 . 9 . 10 . 11 KEY 12 LINES DELETED 13 Yes indeed, deleted

Más respuestas (0)

Categorías

Más información sobre Data Import and Export en Help Center y File Exchange.

Productos


Versión

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by