How to get line number in a text file with a specific word
Show older comments
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
More Answers (1)
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
Jaffrey Hudson Immanuel Jeyakumar
on 22 Jun 2019
infinity
on 22 Jun 2019
Hello,
I realized that in my code, we could not read a sentence properly.
To avoid this problem, you should replace
A = textscan(fileID,'%s');
by
A = textscan(fileID,'%s','delimiter',sprintf('\f'));
Also, to find line number you can refer solution of @madhan ravi
Jaffrey Hudson Immanuel Jeyakumar
on 22 Jun 2019
infinity
on 22 Jun 2019
Hello,
Could you show us what is the errors of your code?
Also, it is better if you can provide a part of text file. So, we could be easy to approach the problem.
Jaffrey Hudson Immanuel Jeyakumar
on 22 Jun 2019
infinity
on 22 Jun 2019
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
clear
fileID = fopen('fruit.txt','r');
A = textscan(fileID,'%s','delimiter',sprintf('\f'));
fclose(fileID);
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))
Jaffrey Hudson Immanuel Jeyakumar
on 22 Jun 2019
Edited: madhan ravi
on 22 Jun 2019
Categories
Find more on Large Files and Big Data in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!