How to measure the depth of a file system path?

2019-08-05 17:26发布

I'm looking for a way to do this on the command line, since this is not too hard a task in Java or Python.

Something like:

$ measure_depth /a/b/c/d/e/f
6
$ measure_depth /a
1

This question is functionally equivalent to "is there an easy way to count the number of slashes in a filename?"

3条回答
聊天终结者
2楼-- · 2019-08-05 17:27

Use realpath before counting the slashes to avoid overestimations as e.g. /home/user/../user/../user/../user/dir/ would be translated to /home/user/dir.

realpath <dir> | grep -o '/' | wc -l
查看更多
爷、活的狠高调
3楼-- · 2019-08-05 17:29

Define a measure_depth function:

measure_depth() { echo "${*#/}" | awk -F/ '{print NF}'; }

Then, use it as follows:

$ measure_depth /a/b/c/d/e/f
6
$ measure_depth /a
1
查看更多
混吃等死
4楼-- · 2019-08-05 17:50

You can do something like

tr -s "/" "\n" | wc -l

which gives you an extra one, so a "hacky" way around it would be

sed "s/^\///" | tr -s "/" "\n" | wc -l

echo "/a/b/c/d/e/f" | sed "s/^\///" | tr -s "/" "\n" | wc -l
6
查看更多
登录 后发表回答