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