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