当前位置: 动力学知识库 > 问答 > 编程问答 >

bash - 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.

网友答案:

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
网友答案:

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

分享给朋友:
您可能感兴趣的文章:
随机阅读: