如何测量文件系统路径的深度?
How to measure the depth of a file system path?
我正在寻找一种在命令行上执行此操作的方法,因为这在 Java
或 Python
中不是太难的任务。
类似于:
$ measure_depth /a/b/c/d/e/f
6
$ measure_depth /a
1
这个问题在功能上等同于"is there an easy way to count the number of slashes in a filename?"
你可以这样做
tr -s "/" "\n" | wc -l
这给了你一个额外的,所以 "hacky" 绕过它的方法是
sed "s/^\///" | tr -s "/" "\n" | wc -l
echo "/a/b/c/d/e/f" | sed "s/^\///" | tr -s "/" "\n" | wc -l
6
定义一个measure_depth函数:
measure_depth() { echo "${*#/}" | awk -F/ '{print NF}'; }
然后,按如下方式使用:
$ measure_depth /a/b/c/d/e/f
6
$ measure_depth /a
1
在计算斜杠之前使用 realpath
以避免高估,例如/home/user/../user/../user/../user/dir/
将被翻译成 /home/user/dir
.
realpath <dir> | grep -o '/' | wc -l
我正在寻找一种在命令行上执行此操作的方法,因为这在 Java
或 Python
中不是太难的任务。
类似于:
$ measure_depth /a/b/c/d/e/f
6
$ measure_depth /a
1
这个问题在功能上等同于"is there an easy way to count the number of slashes in a filename?"
你可以这样做
tr -s "/" "\n" | wc -l
这给了你一个额外的,所以 "hacky" 绕过它的方法是
sed "s/^\///" | tr -s "/" "\n" | wc -l
echo "/a/b/c/d/e/f" | sed "s/^\///" | tr -s "/" "\n" | wc -l
6
定义一个measure_depth函数:
measure_depth() { echo "${*#/}" | awk -F/ '{print NF}'; }
然后,按如下方式使用:
$ measure_depth /a/b/c/d/e/f
6
$ measure_depth /a
1
在计算斜杠之前使用 realpath
以避免高估,例如/home/user/../user/../user/../user/dir/
将被翻译成 /home/user/dir
.
realpath <dir> | grep -o '/' | wc -l