18

我想获取当前级别的文件夹列表(不包括它们的子文件夹),并简单地打印文件夹名称和文件夹中文件的数量(如果可能,最好过滤到 *.jpg)。

这在标准 bash shell 中可行吗?ls -l打印除文件数以外的所有内容:)

4

5 回答 5

21

我想出了这个:

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阻止它打印.(当前目录)作为它搜索的另一个目录。

于 2009-03-10T02:09:51.547 回答
10

在我已经找到了自己的类似脚本之后,我发现了这个问题。它似乎适合您的条件并且非常灵活,因此我想将其添加为答案。

好处:

  • 可以分组到任何深度(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
于 2013-08-28T07:18:25.023 回答
9

我的从命令行输入更快。:)

其他建议是否比以下建议提供任何真正的优势?

find -name '*.jpg' | wc -l               # recursive


find -maxdepth 1 -name '*.jpg' | wc -l   # current directory only
于 2009-03-10T02:25:36.703 回答
1
#!/bin/bash
for dir in `find . -type d | grep -v "\.$"`; do
echo $dir
ls $dir/*.jpg | wc -l
done;
于 2009-03-10T02:10:40.873 回答
1

您可以在没有外部命令的情况下执行此操作:

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]++ }'
于 2009-03-10T10:33:55.920 回答