在linux的目录中查找与模式匹配的文件数 [英] Find count of files matching a pattern in a directory in linux

查看:25
本文介绍了在linux的目录中查找与模式匹配的文件数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 linux 新手.我在 linux 中有一个包含大约 250,000 个文件的目录我需要找到与模式匹配的文件数.

I am new to linux. I have a directory in linux with approx 250,000 files I need to find count of number of files matching a pattern.

我尝试使用以下命令:

ls -1 20061101-20131101_kh5x7tte9n_2010_* | wc -l

我收到以下错误消息:

-bash: /bin/ls: Argument list too long
0

请帮忙.提前致谢

推荐答案

使用 find 可能会更好:

find . -name "pattern_*" -printf '.' | wc -m

在您的具体情况下:

find . -maxdepth 1 -name "20061101-20131101_kh5x7tte9n_2010_*" -printf '.' | wc -m

find 将返回符合条件的文件列表.-maxdepth 1 将使搜索仅在路径中完成,没有子目录(感谢Petesh!).-printf '.' 将为每个匹配项打印一个点,因此带有新行的名称不会使 wc -m 中断.

find will return a list of files matching the criteria. -maxdepth 1 will make the search to be done just in the path, no subdirectories (thanks Petesh!). -printf '.' will print a dot for every match, so that names with new lines won't make wc -m break.

然后wc -m 会指明与文件数匹配的字符数.

Then wc -m will indicate the number of characters which will match the number of files.

两种可能方案的性能比较:

Performance comparation of two possible options:

让我们用这个模式创建 10 000 个文件:

Let's create 10 000 files with this pattern:

$ for i in {1..10000}; do touch 20061101-20131101_kh5x7tte9n_201_$i; done

然后用ls -1 ...find ...比较得到结果所需要的时间:

And then compare the time it takes to get the result with ls -1 ... or find ...:

$ time find . -maxdepth 1 -name "20061101-20131101_kh5x7tte9n_201_*" | wc -m
10000

real    0m0.034s
user    0m0.017s
sys     0m0.021s

$ time ls -1 | grep 20061101-20131101_kh5x7tte9n_201 | wc -m
10000

real    0m0.254s
user    0m0.245s
sys     0m0.020s

find 快了 5 倍!但是如果我们使用 ls -1f (再次感谢Petesh!),那么ls甚至比find还要快:

find is x5 times faster! But if we use ls -1f (thanks Petesh again!), then ls is even faster than find:

$ time ls -1f | grep 20061101-20131101_kh5x7tte9n_201 | wc -m
10000

real    0m0.023s
user    0m0.020s
sys     0m0.012s

这篇关于在linux的目录中查找与模式匹配的文件数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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