How to get line number in a text file with a specific word
43 次查看(过去 30 天)
显示 更早的评论
Jaffrey Hudson Immanuel Jeyakumar
2019-6-22
评论: Jaffrey Hudson Immanuel Jeyakumar
2019-7-17
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 ?
0 个评论
采纳的回答
madhan ravi
2019-6-22
编辑:madhan ravi
2019-6-22
No loops needed:
A = regexp(fileread('fruit.txt'),'\n','split');
whichline = find(contains(A,'apple'))
6 个评论
更多回答(1 个)
infinity
2019-6-22
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Text Files 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!