muyustan
muyustan

Reputation: 1585

How to read a specific line of a .txt file in MATLAB

Assume I have a .txt file as below:

2
3
jack
hello
46
87
928
morning

I saw fgetl() funtion to read data line-by-line. However, it is working in such way that, when it is called first time, it takes the first line and when it is called second time it takes the second line an it goes on like that.

However, what I want to do is, to read a specific line(which I can specify).

For example I want to read line 8 first then line 2 and line 5.

How can I do that?

Thanks.

Upvotes: 0

Views: 4796

Answers (2)

benJephunneh
benJephunneh

Reputation: 736

A quick way is to use a regex search:

fr = fileread('textfile.txt');
matches = regexp(fr, '[^\n]*', 'match'); % 'matches' will be a cell array.  regexp search for '[^\n]*' returns elements separated by newline characters.

% Lines 8, 2, and 5:
matches{8}
matches{2}
matches{5}

Upvotes: 1

Luis Mendo
Luis Mendo

Reputation: 112679

Here's a way to read a specific line:

filename = 'file.txt'; % define file name
n_line = 3; % define line to read
fid = fopen(filename); % open file
result = textscan(fid, '%s', 1, 'Headerlines', n_line-1, 'Delimiter' ,''); % read line
result = result{1}; % unbox from cell
fclose(fid); % close file

If you need to read several lines, you can use a loop as follows:

filename = 'file.txt'; % define file name
n_lines = [3 7 4]; % define lines to read
fid = fopen(filename); % open file
result = cell(1,numel(n_lines));
for n = 1:numel(n_lines)
    result(n) = textscan(fid, '%s', 1, 'Headerlines', n_lines(n)-1, 'Delimiter' ,'');
    frewind(fid) % set file position back to the start
end
result = [result{:}]; % unbox from cells
fclose(fid); % close file

Upvotes: 2

Related Questions