필터 지우기
필터 지우기

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!

채택된 답변

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