Linux 用于列出具有文件计数的文件夹的UNIX命令
我想获得当前级别的文件夹列表(不包括其子文件夹),只需打印文件夹名称和文件夹中的文件数(如果可能,最好过滤为*.jpg)Linux 用于列出具有文件计数的文件夹的UNIX命令,linux,bash,unix,shell,command,Linux,Bash,Unix,Shell,Command,我想获得当前级别的文件夹列表(不包括其子文件夹),只需打印文件夹名称和文件夹中的文件数(如果可能,最好过滤为*.jpg) 在标准bashshell中可以这样做吗ls-l打印除文件计数以外的所有内容:)我想出了这个: find -maxdepth 1 -type d | while read dir; do count=$(find "$dir" -maxdepth 1 -iname \*.jpg | wc -l) echo "$dir ; $count" done 如果目录中
在标准bashshell中可以这样做吗
ls-l
打印除文件计数以外的所有内容:)我想出了这个:
find -maxdepth 1 -type d | while read dir; do
count=$(find "$dir" -maxdepth 1 -iname \*.jpg | wc -l)
echo "$dir ; $count"
done
如果目录中jpg文件的搜索应该是递归的,则删除第二个-maxdepth 1
。请注意,这只考虑文件的名称。您可以重命名文件,隐藏它是jpg图片。您可以使用file
命令对内容进行猜测(现在,还可以递归搜索):
但是,这要慢得多,因为它必须读取部分文件并最终解释它们包含的内容(如果幸运的话,它会在文件的开头找到一个神奇的id)。
-mindepth 1
阻止它将
(当前目录)打印为搜索的另一个目录 从命令行键入mine更快。:)
#!/bin/bash
for dir in `find . -type d | grep -v "\.$"`; do
echo $dir
ls $dir/*.jpg | wc -l
done;
其他建议是否比以下建议更具优势
find -name '*.jpg' | wc -l # recursive
find -maxdepth 1 -name '*.jpg' | wc -l # current directory only
您可以在不使用外部命令的情况下执行此操作:
for d in */; do
set -- "$d"*.jpg
printf "%s: %d\n" "${d%/}" "$#"
done
或者您可以使用awk(Solaris上的nawk或/usr/xpg4/bin/awk):
我发现这个问题之前,我已经想出了我自己的类似脚本。它似乎适合你的条件,而且非常灵活,所以我想我会添加它作为一个答案 优势:
find -P . -type f | rev | cut -d/ -f2- | rev | \
cut -d/ -f1-2 | cut -d/ -f2- | sort | uniq -c
- 可以分组到任何深度(0表示
,1表示一级子目录等) - 打印漂亮的输出
- 没有循环,只有一个
命令,因此在大目录上速度更快find
- 仍然可以调整以添加自定义过滤器(maxdepth使其成为非递归的文件名模式)
find -P . -type f | rev | cut -d/ -f2- | rev | \
cut -d/ -f1-2 | cut -d/ -f2- | sort | uniq -c
包装成函数并解释:
fc() {
# Usage: fc [depth >= 0, default 1]
# 1. List all files, not following symlinks.
# (Add filters like -maxdepth 1 or -iname='*.jpg' here.)
# 2. Cut off filenames in bulk. Reverse and chop to the
# first / (remove filename). Reverse back.
# 3. Cut everything after the specified depth, so that each line
# contains only the relevant directory path
# 4. Cut off the preceeding '.' unless that's all there is.
# 5. Sort and group to unique lines with count.
find -P . -type f \
| rev | cut -d/ -f2- | rev \
| cut -d/ -f1-$((${1:-1}+1)) \
| cut -d/ -f2- \
| sort | uniq -c
}
产生如下输出:
$ fc 0
1668 .
$ fc # depth of 1 is default
6 .
3 .ssh
11 Desktop
44 Downloads
1054 Music
550 Pictures
当然,对于第一个数字,可以通过管道将其发送到sort
:
$ fc | sort
3 .ssh
6 .
11 Desktop
44 Downloads
550 Pictures
1054 Music
对于投票结果接近的人:bash是一种真正的语言。例如:老师想列出他的学生的jpg图片。因此,他将命令放在/home中,并希望在这些子目录中列出所有jpg,以验证它们不包含***内容:)我以前的unix老师的示例。他知道自己在说什么:p PPL试图将其pr0n隐藏在bin文件中:数据只打印文件总数,而不是每个文件夹的数量。按照上面的评论,我现在已经做了。@Dispendengtoat,我误解了你的问题。很抱歉。我现在明白了。我记不起
wc
,所以这对我很有用,尽管它没有完全回答最初的问题。谢谢,@m42martin!在Solaris上没有可用的rev
。您可以使用perl
作为通用解决方案:find-P-键入f | perl-lpe'$\=reverse'| cut-d/-f2-| perl-lpe'$\=reverse'| cut-d/-f1-2 | cut-d/-f2-| sort | uniq-c
$ fc | sort
3 .ssh
6 .
11 Desktop
44 Downloads
550 Pictures
1054 Music