Azzera filtri
Azzera filtri

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

9 visualizzazioni (ultimi 30 giorni)
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!

Risposta accettata

Walter Roberson
Walter Roberson il 7 Set 2022
Modificato: Walter Roberson il 7 Set 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

Più risposte (0)

Categorie

Scopri di più su Data Import and Export in Help Center e File Exchange

Prodotti


Release

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by