readlines
Reads the lines of a text file into a string array.
Category: Data Import and Analysis > Data Import and Export
Syntax
lines = readlines(filename)
Returns one string per line, as a column.
Description
This is the shortest way to loop over the lines of a file: for ln = readlines(f)'. Because the result is a string array, you can use contains, startsWith, split and str2double on all lines at once.
Input arguments
filename- Name of a text file.
Output arguments
lines- Column string array, one element per line, without line terminators.
Example
Filter lines
fid = fopen('log.txt', 'w');
fprintf(fid, 'ok 1\nerror 2\nok 3\nerror 4');
fclose(fid);
L = readlines('log.txt')
L(startsWith(L, 'error'))
Output
L = 4×1 string array
"ok 1"
"error 2"
"ok 3"
"error 4"
ans = 2×1 string array
"error 2"
"error 4"
Notes
When the file ends with a newline, the result includes a final empty string.