在Bash中提取最后两个斜杠之间的字符串

Sas*_*sha 3 bash

我知道可以使用正则表达式轻松完成此操作,就像我在/sf/answers/2336588201/上回答的那样,但是我需要在bash中执行此操作。

因此,我在Stackoverflow上发现的最接近的问题是这一次打击:为路径名提取最后两个dirs,但是区别在于,如果

DIRNAME = /a/b/c/d/e
Run Code Online (Sandbox Code Playgroud)

然后我需要提取

d
Run Code Online (Sandbox Code Playgroud)

Cha*_*ffy 5

这可能会比较长,但是执行起来也比大多数先前的答案(除了zsh-only和ja的答案)要快得多,因为它仅使用内置在bash中的字符串操作,并且不使用subshel​​l扩展:

string='/a/b/c/d/e'  # initial data
dir=${string%/*}     # trim everything past the last /
dir=${dir##*/}       # ...then remove everything before the last / remaining
printf '%s\n' "$dir" # demonstrate output
Run Code Online (Sandbox Code Playgroud)

printf在上面使用了,因为echo它不能对所有值都可靠地工作(请考虑使用来在GNU系统上做什么/a/b/c/-n/e)。


Sas*_*sha 1

天哪,也许这是显而易见的,但最初对我来说并非如此。我得到了正确的结果:

dir=$(basename -- "$(dirname -- "$str")")
echo "$dir"
Run Code Online (Sandbox Code Playgroud)