【问题标题】:counting the number of files in a directory with a command line argument in bash在bash中使用命令行参数计算目录中的文件数
【发布时间】:2021-11-13 09:12:17
【问题描述】:

我想编写一个 bash 脚本,以便计算目录中存在的文件数。此外,它将需要接受一个命令行参数,该参数将是目录路径。我还希望它打印 {directory} has {number of files} 个文件。

例如 my_project has 3 files

我试过ls /$@/ | wc -l 似乎不能正常工作

【问题讨论】:

标签: linux bash shell


【解决方案1】:

您可以使用统计指定目录中的文件

ls -1F $dir_path | grep -v / | wc -l

地点:

  • ls -1F $dir_path 列出$dir_path 中的文件和文件夹

    -- -1 每行列出一个文件

    -- -F 将指示符附加到条目(*/=>@| 之一)

    -- $dir_path 保存传递给脚本的参数

  • grep -v / 过滤掉目录(如果有的话)

  • wc -l 计算代表文件的剩余行数

如果您想包含隐藏文件 - 将 -A 标志添加到 ls


(基本)最终脚本如下所示:
#!/bin/bash
# Set dir_path to current directory to support execution without arguments
dir_path="."
if [ $# -eq 1 ]; then
  dir_path="$1"
fi

num_of_files=$(ls -1F $dir_path | grep -v / | wc -l)

echo "Directory ${dir_path} have ${num_of_files} files."

【讨论】:

    【解决方案2】:

    使用 bash,您可以生成一个字符串,其长度正好是目录中的条目数。

    #!/usr/bin/env bash
    
    count_entries() {
      # Count entries in current directory
    
      local -i dotglob=0 nullglob=0
      local -- all='' dirs=''
    
      # Save current settings
      shopt -q dotglob || dotglob=1
      shopt -q nullglob || nullglob=1
    
      # Need both globbing to count entries in directory
      shopt -s dotglob nullglob
    
      # Turn entries in directory into a string
      printf -v all -- '%.1s' *
    
      # Turn directory entries into a string
      printf -v dirs -- '%.1s' */
    
      # Restore settings
      [ "$dotglob" -eq 1 ] && shopt -u dotglob
      [ "$nullglob" -eq 1 ] && shopt -u nullglob
    
      # Number of entries are length of strings
      local -i a="${#all}"
      local -i d="${#dirs}"
      local -i f=$((a - d))
    
      # Print space delimited values
      printf '%d %d %d\n' "$a" "$d" "$f"
    }
    
    read -r entries directories files < <(count_entries)
    printf 'In %s there are:\n%d entries\n%d directories\n%d files\n' "$PWD" \
      "$entries" "$directories" "$files"
    

    【讨论】:

      【解决方案3】:
      #!/bin/bash
      set -e
      
      shopt -s extglob
      (($# == 1))
      for p in "${1}/"?(.@([^.]|.?))*; do
        [[ -f "$p" ]] && ((++counter)) || :
      done
      printf '%s\n' "${path} has $((counter)) files"
      

      【讨论】:

      • 代码在附有解释时会更有帮助。 Stack Overflow 是关于学习的,而不是提供 sn-ps 来盲目复制和粘贴。请edit您的问题并解释它如何回答所提出的具体问题。见How to Answer
      猜你喜欢
      • 2018-03-25
      • 2016-12-15
      • 2013-12-07
      • 1970-01-01
      • 2017-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多