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

9 次查看(过去 30 天)
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!

采纳的回答

Walter Roberson
Walter Roberson 2022-9-7
编辑:Walter Roberson 2022-9-7
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Data Import and Export 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by