计算文件夹中文本文件中的行数,并使用MATLAB计算总行数 [英] Count the number of lines in text files in a folder and sum the number of the total lines using MATLAB

查看:1116
本文介绍了计算文件夹中文本文件中的行数,并使用MATLAB计算总行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读取一些文本文件,它们在MATLAB的一个文件夹中,计算每个文件中的行数,最后总结这些数字。如果有人指导我如何在MATLAB中做它,我会感激的。

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?

推荐答案

Matlab真的不适合。

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

请注意,除非


  • 如果您使用的是Linux / max,并且在当前目录中有一个名为 total 的文件: )

  • Windows版本有时会错误计数一些文件1或2行,我不知道为什么...

  • 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...

我确定有一个更清洁的一行解决方案来解析linux结果字符串;当前的麻烦是由于 regexp(...,'tokens')返回一个单元格,这对当前上下文很不方便说实话,我还没有发现很多上下文方便的地方),所以这必须由 cellfun 解决。

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.

这篇关于计算文件夹中文本文件中的行数,并使用MATLAB计算总行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆