how to search and delete the nth ocurance of a text in a text file

2 ビュー (過去 30 日間)
Jaffrey Hudson Immanuel Jeyakumar
Jaffrey Hudson Immanuel Jeyakumar 2019 年 7 月 17 日
コメント済み: madhan ravi 2019 年 7 月 17 日
Hallo,
I have a text file 'test.txt' . The contents of test file is as follows.
Tim is Home
John is happy
Sara is funny
Kevin is at work
John is happy
Cat and Dog
I want to open the test.txt file and delete the 'nth' occurance of 'John is happy '. I have attached the text file too. Thanks in advance.
eg. I want to delete the line with ' n th 'occurance.
so It can be 1st occurance
or 2nd Occurance.. etc
Regards,
Jaffrey

採用された回答

madhan ravi
madhan ravi 2019 年 7 月 17 日
s = fileread('test.txt');
v = regexp(s,'\n','split');
z = regexprep(s,'John is happy','',2) % 2 denotes the nth occurence
dlmwrite('sample.txt',z,'delimiter','')
  4 件のコメント
Adam Danz
Adam Danz 2019 年 7 月 17 日
Is that hunch from your crystal ball? :D
madhan ravi
madhan ravi 2019 年 7 月 17 日
Exactly XD

サインインしてコメントする。

その他の回答 (2 件)

Adam Danz
Adam Danz 2019 年 7 月 17 日
編集済み: Adam Danz 2019 年 7 月 17 日
The question is unclear whether the goal is to remove the 2nd line of text or to remove the line(s) with "John is happy". The block below shows both interpretations.
% Import text
opts = delimitedTextImportOptions("NumVariables", 1);
opts.VariableNames = "txt";
test = readtable("C:\Users\adanz\Documents\MATLAB\savehere\matlabCentralDocs_trash\test.txt", opts);
test = table2array(test);
% Delete 2nd line
test(2) = [];
% - OR -
% Delete lines that match "John is happy"
idx = strcmpi(test, 'John is happy');
test(idx) = [];
% - OR -
% delete nth occurance of "John is happy"
n = 2;
idx = strcmpi(test, 'John is happy');
test(max(find(idx,n))) = [];
% Write to txt file
fid = fopen('test2.txt','wt');
fprintf(fid,'%s\n',test{:});
fclose(fid);
  3 件のコメント
Adam Danz
Adam Danz 2019 年 7 月 17 日
OK, see updated answer.
Jaffrey Hudson Immanuel Jeyakumar
Jaffrey Hudson Immanuel Jeyakumar 2019 年 7 月 17 日
Thank you ! for the update .

サインインしてコメントする。


Jaffrey Hudson Immanuel Jeyakumar
Jaffrey Hudson Immanuel Jeyakumar 2019 年 7 月 17 日
Thank you. It is working now.

カテゴリ

Help Center および File ExchangeText Files についてさらに検索

製品


リリース

R2015b

Community Treasure Hunt

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

Start Hunting!

Translated by