我在 Win10 计算机上工作,但我通常在 Gitbash 或 linux 子系统上工作。
我正在尝试获取指定目录的所有子目录中的文件数。
这是与如何报告所有子目录中的文件数类似的问题?但不同的是,我在所有子目录上都没有固定数量的级别,我有类似的东西:
Dir1/sub1
Dir1/sub1/subsub1
Dir1/sub2
Dir1/sub3/subsub3/subsubsub3
Run Code Online (Sandbox Code Playgroud)
我试过
shopt -s dotglob; for dir in */; do all=("$dir"/*); echo "$dir: ${#all[@]}"; done
Run Code Online (Sandbox Code Playgroud)
玩弄要搜索的级别数 (* /,* /* /* 等等)
但我无法真正得到我正在寻找的东西,例如:
Dir1/sub1: Number of files
Dir1/sub2: Number of files
Dir1/sub3: Number of files
Run Code Online (Sandbox Code Playgroud)
我不熟悉 Windows 上的 Gitbash,但我假设无论您在什么平台上运行此脚本,您都安装了这些:
bash
v4.x 或更高版本(macOS 用户需要通过Homebrew或其他方式安装更新版本)find
真的,任何标准的 Unix 都find
可以,只是 MS-DOS/Windows 版本不行(更像是grep
)假设上述情况,这个脚本应该可以解决问题:
#!/bin/bash
# USAGE: count_files <dir> ...
declare -A filecount
# Tell bash to execute the last pipeline element in this shell, not a subshell
shopt -s lastpipe
# Run through all the user-supplied directories at one go
for d in "$@"; do
find "$d" -type f | while read f; do
[[ $f =~ ^(${d%%/}/[^/]+)/ ]] && (( filecount["${BASH_REMATCH[1]}"]++ ))
done
done
# REPORT!
for k in "${!filecount[@]}"; do
echo "$k: ${filecount[$k]}"
done
Run Code Online (Sandbox Code Playgroud)