1

In Ubuntu graphical user-interface, I can list the sub-directories in a directory where one column represents the number of items in these sub-directories. As shown here:

nautilus screenshot

Is there a way to get the same result (number of items in size column) using the command line?

3

1 Answer 1

3

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):

$ tree
.
├── a bad one
│   └── file 1
├── a bad worse\012one
│   └── file 1 \012two
├── dir1
│   └── file
├── dir2
│   ├── file1
│   └── file2
├── dir3
│   ├── file1
│   ├── file2
│   └── file3
├── dir4
│   └── dir
├── empty_dir

8 directories, 7 files

You would get:

$ lsc 
./a bad one/ (1)
./a bad worse
one/ (1)
./dir1/ (1)
./dir2/ (2)
./dir3/ (3)
./dir4/ (1)
./empty_dir/ (0)
./mp3/ (1)

The main advantages of this approach are:

  1. You can run it on multiple directories:

    lsc /path/to/dir /path/to/dir2 ... /path/to/dirN
    

    Or on the current one:

    lsc
    
  2. It can work on arbitrary file and directory names, even those containing spaces or newline characters as you can see above.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .