问题
How can I write a shell script to find the depth of the current path?
Assuming I am in:
/home/user/test/test1/test2/test3
It should return 6.
回答1:
A simple approach in fish:
count (string split / $PWD)
回答2:
With shell parameter expansions, no external commands:
$ var=${PWD//[!\/]}
$ echo ${#var}
6
The first expansion removes all characters that are not /; the second one prints the length of var.
Explanations with details for support by POSIX shell or Bash (the links in parentheses go to the corresponding sections in the POSIX standard or the Bash manual):
$PWDcontains the path to the current working directory. (sh/Bash)- The
${parameter/pattern/string}expansion replaces the first occurrence ofpatternin the expansion ofparameterwithstring. (Bash)- If the first slash is doubled (as in our case), all occurrences are replaced.
- If
stringis empty, the slash afterpatternis optional (as in our case).
- The pattern
[!\/]is a bracket expression and stands for "any character other than slash". (sh/Bash)- The slash has to be escaped,
\/, or it is interpreted as ending the pattern. !as the first character in a bracket expression negates the expression: any character other than the ones in the expression match the pattern. POSIX sh requires support for!and says the behaviour for using^is undefined; Bash supports both!and^. Notice that this is not a bracket expression as seen in regular expressions, where only^is valid.
- The slash has to be escaped,
${#parameter}expands to the length ofparameter. (sh/Bash)
回答3:
You could count the number of slashes in the current path:
pwd | awk -F"/" '{print NF-1}'
回答4:
Assuming you don't have trailing "/", you can just count the "/".
So you would
Remove everything that is not a "/"
Count the length of the resulting string
In fish, this would be done with something like
string replace --regex --all '[^/]' '' -- $PWD | string length
The regular expression - [^/] here matches every single character that is not a "/". With "--all", this will be done as often as possible, and replace it with '', i.e. nothing.
The -- is the option separator, so that nothing in the argument is interpreted as an option (otherwise you'd have issues if an argument started with a "-a").
$PWD is the current directory.
string length simply outputs the length of its input.
回答5:
You can do this using a pipeline. pipe string into grep with the -o option. This prints out each "/" on a new line. pipe again into wc -l counts the number of lines printed.
echo "$path_str" | grep -o '/' - | wc -l
回答6:
Using perl :
echo '/home/user/test/test1/test2/test3' |
perl -lne '@_ = split /\//; print scalar @_ -1'
Output
6
回答7:
You could use find just like that :
find / -printf "%d %p\n" 2>/dev/null | grep "$PWD$" | awk '{print $1}'
Maybe not the most efficient, but handles slashes well.
来源:https://stackoverflow.com/questions/48816827/find-the-depth-of-the-current-path