0

I need to write a program in matlab that searches for key words in a text file and then reads in what comes after those words, then continue searching.i tried to use fscanf or textscan but i must be missing something

I have a text file and the content looks like this:

Maria, female,24,married
       born in USA

George, male,32,married
        born in Germany    

There is an empty line before name George. For example, i want to read Maria and then read what comes after word Maria until the empty line.

michael
  • 57
  • 2
  • 10
  • 1
    you probably don't want to hear this, but Matlab is hardly the right tool for text processing. I would recommend first perl (because I'm so used to it), but since many people don't like it, I'll say that python would be a good choice too, and a much better one than Matlab. – carandraug Feb 12 '14 at 11:13
  • The question is not clear for me... What are you expecting? Are you expecting a different method that improves the speed of searching or reading? Or are you expecting a method to parse the output of texscan? – phyrox Feb 12 '14 at 12:01
  • also, when you say _i tried to use fscanf or textscan but i must be missing something_, please [see this](http://www.phabricator.com/docs/phabricator/article/Please_Please_Please.html) otherwise we can't help you. – carandraug Feb 12 '14 at 12:07
  • Use textscan to read file into a cell array of lines. Then use strcmp and length to identify lines starting with Maria and blank ones, you can use those indices to extract the required lines. Posting your code with textscan would help to identify why it didn't work. – Adrian Feb 12 '14 at 12:27

1 Answers1

4

You can use textscan to read the whole file, search for a keyword, extract the line found and then concatenate this line with the next line.

Here is an example, looking for Maria

fid = fopen('textfile.txt','r')
C = textscan(fid, '%s','Delimiter','');
fclose(fid)
C = C{:};

Lia = ~cellfun(@isempty, strfind(C,'Maria'));

output = [C{find(Lia)} ',' C{find(Lia)+1}]

which gives

Maria, female,24,married,born in USA
marsei
  • 7,691
  • 3
  • 32
  • 41