4

I'm using command find to recursively browse through directory tree, counting files, sizes, etc...

Now I need to get directory depth of each file. Is there any portable way for both FreeBSD and CentOS?

I know that find is able to prinf actual directory depth but sadly this works only on CentOS, not FreeBSD.

Additionaly - I need to keep standard find output OR put directory depth on the beginning of output and cut it from there.

Mára Toner
  • 302
  • 2
  • 16

2 Answers2

9

You can count the / in path :

$ find . -type f -exec bash -c 'echo '{}' | grep -o / | wc -l' \;

Or with file names :

$ mkdir -p one/two/three four/five && touch file one/two/file one/two/three/file
$ find . -type f -exec bash -c 'echo -n '{}' :; echo '{}' | grep -o / | wc -l' \;
./file :1
./one/two/file :3
./one/two/three/file :4
SLePort
  • 15,211
  • 3
  • 34
  • 44
1

Try this:

find . -type d -exec bash -c 'echo $(tr -cd / <<< "$1"|wc -c):$1' -- {} \; | sort -n | tail -n 1 | awk -F: '{print $1, $2}'

JonatasTeixeira
  • 1,474
  • 1
  • 18
  • 24