Home > Mobile >  Directory Content Count Using Linux Find Command
Directory Content Count Using Linux Find Command

Time:10-29

How can I populate the placeholder [COUNT] in the following Linux find command with total number of files plus folders for each sub-directory inside SomeFolder where am using bash:

find '/SomeFolder' -maxdepth 1 -mindepth 1 -type d -printf '%f **[COUNT]**\n' | sort

CodePudding user response:

If you use find just to print out the directories, then pipe the output to xargs to produce the counts, you could write it like this:

find '/SomeFolder' -maxdepth 1 -mindepth 1 -type d -print0 |
  xargs -0 -IDIR sh -c 'echo "$(basename "DIR"): $(ls "DIR" | wc -l)"' |
  sort

Which gets you output like:

android-otp-extractor: 1
ansible: 13
argocd-app-of-app-chart: 1
asan: 0
asm: 0
aws-secrets: 0
backup: 0

But as @Jetchisel said, you don't really need find for what you're doing; this should get you the same thing:

ls --zero -d /SomeFolder/*/ |
  xargs -0 -IDIR sh -c 'echo "$(basename "DIR"): $(ls "DIR" | wc -l)"' |
  sort

(We're using --zero with ls and -print0 with find in order to correctly handle directory names that contain whitespace.)

CodePudding user response:

Not sure if find is really needed with globstar on with bash but, here it is.

#!/usr/bin/env bash

count=0

while IFS= read -rd '' sub_dirs; do
  shopt -s globstar nullglob dotglob
  count=("$sub_dirs"/**)
  shopt -u globstar nullglob dotglob
  printf '%s: %d\n' "$sub_dirs" "${#count[*]}"
done < <(find /Somedir -maxdepth 1 -mindepth 1 -type d -print0) |
sort -k2 -n
  • Related