2019-07-04

How to display number of items in sub-directories from command line



Reference URL:
https://askubuntu.com/questions/1150749/how-to-display-number-of-items-in-sub-directories-from-command-line/1150753#1150753



Here's a little shell function that you can use. Just add these lines to your ~/.bashrc:
lsc(){
    ## globs that don't match should expand to a null string
  shopt -s nullglob
  ## If no arguments were given use the current dir
  if [[ $# -eq 0 ]]; then
    targets="."
  ## Otherwise, use whatever was given
  else
    targets=($@)
  fi
  ## iterate over the arguments given
  for target in "${targets[@]}"; do
    ## get the contents of the target
    contents=("$target"/*)
    ## iterate over the contents
    for thing in "${contents[@]}";  do
      ## If this one is a directory
      if [[ -d "$thing" ]]; then
        ## collect the directory's contents
        count=("$thing"/*)
        ## Print the dir's name (with a '/' at the end)
        ## and the number of items found in it
        printf "%s/ (%s)\n" "$thing" "${#count[@]}"
      else
        ## If this isn't a dir, just print the name
        printf "%s\n" "$thing"
      fi
    done
  done
}
then open a new terminal and run:
lsc /path/to/dir
For example, given the following directory (the \012 are newlines in the names):












No comments:

Google Referrals