我想获取当前级别的文件夹列表(不包括它们的子文件夹),并简单地打印文件夹名称和文件夹中文件的数量(如果可能,最好过滤到 *.jpg)。
这在标准 bash shell 中可行吗?ls -l
打印除文件数以外的所有内容:)
我想出了这个:
find -maxdepth 1 -type d | while read dir; do
count=$(find "$dir" -maxdepth 1 -iname \*.jpg | wc -l)
echo "$dir ; $count"
done
-maxdepth 1
如果在考虑子目录的情况下在目录中搜索 jpg 文件应该是递归的,则删除第二个。请注意,这仅考虑文件的名称。您可以重命名文件,隐藏它是 jpg 图片。您可以使用该file
命令来猜测内容,而不是(现在,也递归搜索):
find -mindepth 1 -maxdepth 1 -type d | while read dir; do
count=$(find "$dir" -type f | xargs file -b --mime-type |
grep 'image/jpeg' | wc -l)
echo "$dir ; $count"
done
但是,这要慢得多,因为它必须读取部分文件并最终解释它们包含的内容(如果幸运的话,它会在文件的开头找到一个神奇的 id)。-mindepth 1
阻止它打印.
(当前目录)作为它搜索的另一个目录。
在我已经找到了自己的类似脚本之后,我发现了这个问题。它似乎适合您的条件并且非常灵活,因此我想将其添加为答案。
好处:
.
,1 表示第一级子目录等)find
命令,所以在大目录上更快一点原始代码:
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
我的从命令行输入更快。:)
其他建议是否比以下建议提供任何真正的优势?
find -name '*.jpg' | wc -l # recursive
find -maxdepth 1 -name '*.jpg' | wc -l # current directory only
#!/bin/bash
for dir in `find . -type d | grep -v "\.$"`; do
echo $dir
ls $dir/*.jpg | wc -l
done;
您可以在没有外部命令的情况下执行此操作:
for d in */; do
set -- "$d"*.jpg
printf "%s: %d\n" "${d%/}" "$#"
done
或者您可以使用awk(在Solaris上是nawk或/usr/xpg4/bin/awk):
printf "%s\n" */*jpg |
awk -F\/ 'END {
for (d in _)
print d ":",_[d]
}
{ _[$1]++ }'