【发布时间】:2010-10-12 08:03:04
【问题描述】:
我想获取当前级别的文件夹列表(不包括其子文件夹),并简单地打印文件夹名称和文件夹中文件的数量(如果可能,最好过滤到 *.jpg)。
这在标准 bash shell 中可行吗? ls -l 打印除文件数以外的所有内容:)
【问题讨论】:
-
致投票接近的人:bash 是一门实际的语言。
标签: linux bash unix shell command
我想获取当前级别的文件夹列表(不包括其子文件夹),并简单地打印文件夹名称和文件夹中文件的数量(如果可能,最好过滤到 *.jpg)。
这在标准 bash shell 中可行吗? ls -l 打印除文件数以外的所有内容:)
【问题讨论】:
标签: linux bash unix shell command
我想出了这个:
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 命令来猜测内容,而不是(现在,也递归搜索):
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 阻止它打印.(当前目录)作为它搜索的另一个目录。
【讨论】:
#!/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
【讨论】:
wc,所以这对我很有用,即使它没有完全回答原始问题。谢谢,@m42martin!
你可以在没有外部命令的情况下做到这一点:
for d in */; do
set -- "$d"*.jpg
printf "%s: %d\n" "${d%/}" "$#"
done
或者您可以使用 awk(nawk 或 /usr/xpg4/bin/awk 在 Solaris 上) :
printf "%s\n" */*jpg |
awk -F\/ 'END {
for (d in _)
print d ":",_[d]
}
{ _[$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
【讨论】:
rev。您可以使用perl 作为通用解决方案:find -P . -type f | perl -lpe'$_ = reverse' | cut -d/ -f2- | perl -lpe'$_ = reverse' | cut -d/ -f1-2 | cut -d/ -f2- | sort | uniq -c