Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get file depth in directory tree

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.

like image 382
Mára Toner Avatar asked Oct 18 '25 19:10

Mára Toner


2 Answers

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
like image 197
SLePort Avatar answered Oct 20 '25 09:10

SLePort


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}'

like image 23
JonatasTeixeira Avatar answered Oct 20 '25 10:10

JonatasTeixeira



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!