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

61 ビュー (過去 30 日間)
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 ?

採用された回答

madhan ravi
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 件のコメント
Jaffrey Hudson Immanuel Jeyakumar
Jaffrey Hudson Immanuel Jeyakumar 2019 年 6 月 22 日
Hallo Madhan,
Thanks for the answer. The script works very fine :)
Regards,
Jaffrey Hudson
Jaffrey Hudson Immanuel Jeyakumar
Jaffrey Hudson Immanuel Jeyakumar 2019 年 7 月 17 日
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 ?

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

その他の回答 (1 件)

infinity
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 件のコメント
Jaffrey Hudson Immanuel Jeyakumar
Jaffrey Hudson Immanuel Jeyakumar 2019 年 6 月 22 日
編集済み: madhan ravi 2019 年 6 月 22 日
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.
Regards,
Jaffrey Hudson
infinity
infinity 2019 年 6 月 22 日
編集済み: infinity 2019 年 6 月 22 日
Good for you.

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

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by