String search

12 ビュー (過去 30 日間)
sara
sara 2012 年 3 月 4 日
How I can search for a string in a text file and delete all the lines except the lines that have the specific string. Thanks.

回答 (3 件)

Honglei Chen
Honglei Chen 2012 年 3 月 4 日
It is probably easier to write all lines that have the specific string into a new file so you don't have to worry about the file pointer location.
You use fopen to open the file, use fgetl to get the line. Then you can use strfind to check if it has the specific string. If so, write it to the new file using fprintf.
doc fopen
doc fgetl
doc strfind
doc fprintf
Here is an example
fid1 = fopen('old.txt','r');
fid2 = fopen('new.txt','w');
while 1
tline = fgetl(fid1);
if strfind(tline,SPECIFI_STRING)
fprintf(fid2,'%s\n',tline);
end
end
fclose(fid1);
fclose(fid2);
  1 件のコメント
sara
sara 2012 年 3 月 6 日
absolutely your answer is better.

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


Walter Roberson
Walter Roberson 2012 年 3 月 5 日
Read the file in as a complete string, regexp() to find the lines that match the string, write out the matched lines.
OR
Write a very small perl script whose essential code would be
{print if /TheString/}
There is some overhead to invoke it nicely from MATLAB rather than using system(), as system() would allow you the very compact
system('perl -ne "{print if /TheString/}" < InputFile > OutputFile')

sara
sara 2012 年 3 月 6 日
Thanks for the answers.The thing is I try to extract the video from a html file. To do that I want to find the video tags. Do you have any suggestion?
  1 件のコメント
Walter Roberson
Walter Roberson 2012 年 3 月 6 日
Are you looking through an HTML stream for a Content-type: video/SOMETHING
http://www.w3.org/TR/html4/types.html#h-6.7
If you are, then you need to know that the representation of the video will *not* have one such header for each line. Instead, there will be a Content-transfer-encoding header that specifies an encoding type such as base64; then after the end of the mime-headers, there will be an empty line, and then there will be the encoded data for the video. If base64 encoding is used, there will be NO per-line tag indicating the line has video: it will simply be a line of up to 76 encoded characters.
I do not know at the moment what else you might mean by "video tags".

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

カテゴリ

Help Center および File ExchangeEntering Commands についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by