How to get line number in a text file with a specific word

127 views (last 30 days)
Hallo,
I have a fruit.txt file with data as follows,
apple
mango
Cherry
Watermelon
I want to write a script whcih will find the word 'apple' and return me it line number.
Can anyone help me ?

Accepted Answer

madhan ravi
madhan ravi on 22 Jun 2019
Edited: madhan ravi on 22 Jun 2019
No loops needed:
A = regexp(fileread('fruit.txt'),'\n','split');
whichline = find(contains(A,'apple'))
  6 Comments
Jaffrey Hudson Immanuel Jeyakumar
Hallo ,
I need a small help. I have to trim from the second occurance of the search text 'SOF1_ANTIALIASING on surface AXLERIMI' . How can i update the script ?

Sign in to comment.

More Answers (1)

infinity
infinity on 22 Jun 2019
Hello,
you could try this
fileID = fopen('fruit.txt','r');
A = textscan(fileID,'%s');
fclose(fileID);
n = size(A{:});
for i = 1:n
if strcmp(A{:}(i),'apple')
linenumber = i;
end
end
  8 Comments

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!