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);

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 CenterFile Exchange 中查找有关 Entering Commands 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by