问题
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