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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值