0

Can I get help fixing my code to count every subdirectory (excluding "PATH" itself)?

num_directories=$( find $dir -type d | wc -l)

Also need help fixing the total byte count of each file

total_size=$( find $dir -type f -ls | awk '{total+=5}END{print total}';)

I understand you won't have access to the same files but I think the code with the calculations would be the same.

thanasisp
  • 5,855
  • 3
  • 14
  • 31
  • Did you mean `total+=$7`? AND , what do you mean *"excluding "PATH" itself"*? You'll need to give us a reasonable value for `$dir`. If you launched your search with `dir=/usr`, then are you saying you don't want to count `/usr/bin` (as it is usually in the PATH)? The only solution to that would be a "function" that converts the `PATH` value into a bunch of `sed` commands like `/\/usr\/bin/d` that is applied via a pipe in between the output of `find` and the input of `wc`. Good luck. – shellter Oct 03 '20 at 03:58

1 Answers1

0

To count all subdirectories recursively under a directory, excluding the directory itself:

find "$d" -mindepth 1 -type d | wc -l

Example:

> mkdir -p 1; mkdir -p 2
> find . -type d | wc -l
3
> find . -mindepth 1 -type d | wc -l
2

Also do not parse the text output of ls command for any reason, see why here and here.

To print the byte count for all files (recursively) in the current directory:

find -type f -exec wc -c {} +

To get the total as a number alone (retract only the first field of last line)

find -type f -exec wc -c {} + | sed -n '$ s/ .*$//p'

or the same

find -type f -exec wc -c {} + | awk 'END{ print $1}'
thanasisp
  • 5,855
  • 3
  • 14
  • 31