计算目录中的文件编号,其名称中包含空白

时间:2017-09-23 20:16:05

标签: shell unix

     If you want a breakdown of how many files are in each dir under your current dir:

 for i in $(find . -maxdepth 1 -type d) ; do 
    echo -n $i": " ; 
   (find $i -type f | wc -l) ; 
 done

当目录名在名称中有空时,它不起作用。这里的任何人都可以告诉我如何编辑这个shell脚本,以便这些目录名也被接受来计算其文件内容? 感谢

3 个答案:

答案 0 :(得分:2)

您的代码遇到http://mywiki.wooledge.org/BashPitfalls#for_i_in_.24.28ls_.2A.mp3.29中描述的常见问题。

在你的情况下,你可以这样做:

for i in */; do 
    echo -n "${i%/}: " 
    find "$i" -type f | wc -l 
done

答案 1 :(得分:0)

这适用于所有类型的文件名:

find . -maxdepth 1 -type d -exec sh -c 'printf "%s: %i\n" "$1" "$(find "$1" -type f | wc -l)"' Counter {} \;

如何运作

  • find . -maxdepth 1 -type d

    这会像你一样找到目录

  • -exec sh -c 'printf "%s: %i\n" "$1" "$(find "$1" -type f | wc -l)"' Counter {} \;

    这会将每个目录名称提供给shell脚本,该脚本会对文件进行计数,与您正在执行的操作类似。

    这里有一些技巧:Counter {}作为参数传递给shell脚本。 Counter变为$0(仅在shell脚本生成错误时使用。find{}替换为其找到的目录的名称,这将可用于shell脚本为$1。这样做对所有类型的文件名都是安全的。

    请注意,在脚本中使用$1的任何地方,它都在双引号内。这可以保护它免于分词或其他不需要的shell扩展。

答案 2 :(得分:-1)

我找到了我必须考虑的解决方案: Consider_this

  #!/bin/bash
  SAVEIFS=$IFS
  IFS=$(echo -en "\n\b")
  for i in $(find . -maxdepth 1 -type d); do
    echo -n " $i: ";
    (find $i -type f | wc -l) ;
  done
  IFS=$SAVEIFS