How to delete all lines in a text file after a certain word matches
조회 수: 6 (최근 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!
댓글 수: 0
채택된 답변
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)
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Import and Export에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!