I would like to read some text files which are in one folder in MATLAB, count the number of lines in each file and finally sum up these numbers. I would be thankful if somebody guide me how to do it in MATLAB?
2 Answers
To get all the text file names use dir(*.txt)
http://www.mathworks.com/help/matlab/ref/dir.html
To count all the lines see this answer: Is there a way in Matlab to determine the number of lines in a file without looping through each line?
Matlab is really not suited for that. The underlying OS usually is much better at that, so, use a system call.
Rephrasing my original answer from this question (I've learned a few new tricks since then :)
if (isunix) %# Linux, mac
[~, result] = system('wc -l *');
numLines = cellfun(@str2double, regexp(result, '([0-9]+) total', 'tokens'))
elseif (ispc) %# Windows
[~, result] = system('find /v /c "&*fake&*" *.*');
numLines = sum(str2double( regexp(result, '[0-9]+', 'match') ))
else %# Some smaller OS
error('Unsupported operating system.');
end
Note that this will work fine, except
- if you're on Linux/max and have a file called
total
in the current directory :) - the Windows version sometimes miscounts some files by 1 or 2 lines, I don't know why...
I'm pretty sure there is a cleaner one-line-solution to parse the linux result string; the current mess is due to regexp(..., 'tokens')
returning a cell of cells which is pretty inconvenient for the current context (to be honest, I haven't found many contexts where it was convenient yet), so this must be worked-around by cellfun
.
But oh well, it reckon it should do the trick in most circumstances.

- 1
- 1

- 37,726
- 7
- 50
- 96
-
reading the help of `find /?`, I think the reason it would miscount is if the "fake" string thing occurs in the file.. – Amro Apr 19 '13 at 16:40
-
You could always get a port of `wc` on Windows: Cygwin, MSYS/MinGW, [GnuWin32](http://gnuwin32.sourceforge.net/packages/coreutils.htm), [UnxUtils](http://unxutils.sourceforge.net/).. – Amro Apr 19 '13 at 16:53
-
@Amro: True, but I wanted a solution that works without having to install any external tools. – Rody Oldenhuis Apr 19 '13 at 20:37
-
@Amro: ah, well that might be true :) silly me – Rody Oldenhuis Apr 19 '13 at 20:38