MATLAB Answers

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

I have a fruit.txt file with data as follows,
I want to write a script whcih will find the word 'apple' and return me it line number.
Can anyone help me ?


Sign in to comment.

2 Answers

Answer by madhan ravi
on 22 Jun 2019 at 13:09
Edited by madhan ravi
on 22 Jun 2019 at 13:21
 Accepted Answer

No loops needed:
A = regexp(fileread('fruit.txt'),'\n','split');
whichline = find(contains(A,'apple'))


That's why you should tell which version you're using when you ask a question so that the answerers are not riddled by your confusions, contains() - released in 2016b.
Whichline = find(~cellfun('isempty',strfind(A,'I eat apple')))
According to the comment you made in the other answer:
A = regexp(fileread('fruit.txt'),'\n','split');
Whichline = find(~cellfun('isempty',...
strfind(A,'SOF1_ANTIALIASING on surface AXLERIMI')))
Hallo Madhan,
Thanks for the answer. The script works very fine :)
Jaffrey Hudson
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.

Answer by Trung VO DUY on 22 Jun 2019 at 12:47

you could try this
fileID = fopen('fruit.txt','r');
A = textscan(fileID,'%s');
n = size(A{:});
for i = 1:n
if strcmp(A{:}(i),'apple')
linenumber = i;


Since the phase 'SOF1_ANTIALIASING on surface AXLERIMI' is not alone but it is apart in the sentence "Title Step_1_SOF1_ANTIALIASING on surface AXLERIMI[ElementSet__PIBATCH] "
If you change the phase of searching to "Title Step_1_SOF1_ANTIALIASING on surface AXLERIMI[ElementSet__PIBATCH]
", you could obtain the result is this code
fileID = fopen('fruit.txt','r');
A = textscan(fileID,'%s','delimiter',sprintf('\f'));
n = size(A{:});
A = A{:};
% phase = 'SOF1_ANTIALIASING on surface AXLERIMI';
phase = 'Title Step_1_SOF1_ANTIALIASING on surface AXLERIMI[ElementSet__PIBATCH]';
linenumber = find(ismember(A,phase))
Hallo Trung,
I get the following error.
Error using textscan
Invalid file identifier. Use fopen to generate a valid file identifier.
Error in linenumber4 (line 4)
A = textscan(fileID,'%s','delimiter',sprintf('\f'));
Thank a lot for your support. The script from Madhan works now.
Jaffrey Hudson

Sign in to comment.