user3733487
user3733487

Reputation: 33

Read in a file and skip lines that start with a specific string

I'm tryng to read in a text file with Matlab. The file is in this format:

string number number
string number number
....

I'd like to skip the lines which start with a specific string. For any other string, I want to save the two numbers in that line.

Upvotes: 3

Views: 2110

Answers (1)

timgeb
timgeb

Reputation: 78690

Let's take this sample file file.txt:

badstring 1 2
badstring 3 4
goodstring 5 6
badstring 7 8
goodstring 9 10

If a line starts with badstring we skip it, otherwise we store the two numbers following the string.

fid = fopen('file.txt');
nums = textscan(fid, '%s %f %f');
fclose(fid);
ind = find(strcmp(nums{1},'badstring'));
nums = cell2mat(nums(:,2:end));
nums(ind,:) = [];
display(nums)

This will read the entire file into a cell array, then convert it to a matrix (without the strings), and then kill any row which originally started with badstring. Alternatively, if the file is very large, you can avoid the temporary storage of all the lines with this iterative solution:

fid = fopen('file.txt');
line = fgetl(fid); 
numbers = [];
while line ~= -1 % read file until EOF
    line = textscan(line, '%s %f %f');
    if ~strcmp(line{1}, 'badstring')
        numbers = [numbers; line{2} line{3}];
    end
    line = fgetl(fid);
end
fclose(fid); 
display(numbers)

Upvotes: 6

Related Questions