How to measure the depth of a file system path?

限于喜欢 提交于 2020-01-15 10:29:48

问题


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?"


回答1:


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



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/31528199/how-to-measure-the-depth-of-a-file-system-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!