我需要确保字符串中的最后一个字符是/
x="test.com/"
if [[ $x =~ //$/ ]] ; then
x=$x"extention"
else
x=$x"/extention"
fi
目前, false 总是触发。
我需要确保字符串中的最后一个字符是/
x="test.com/"
if [[ $x =~ //$/ ]] ; then
x=$x"extention"
else
x=$x"/extention"
fi
目前, false 总是触发。
像这样,例如:
$ x="test.com/"
$ [[ "$x" == */ ]] && echo "yes"
yes
$ x="test.com"
$ [[ "$x" == */ ]] && echo "yes"
$
$ x="test.c/om"
$ [[ "$x" == */ ]] && echo "yes"
$
$ x="test.c/om/"
$ [[ "$x" == */ ]] && echo "yes"
yes
$ x="test.c//om/"
$ [[ "$x" == */ ]] && echo "yes"
yes
${var:index}
您可以在 Bash 中使用和来索引字符串${#var}
以获取字符串的长度。负索引意味着从字符串的末尾移动到字符串的开头,因此这-1
是最后一个字符的索引:
if [[ "${x:${#x}-1}" == "/" ]]; then
# last character of x is /
fi
你的情况有点不正确。使用=~
时,rhs 被认为是一种模式,所以你会说pattern
and not /pattern/
。
如果你说,你会得到预期的结果
if [[ $x =~ /$ ]] ; then
代替
if [[ $x =~ //$/ ]] ; then
You can do this generically using bash substrings $(string:offset:length}
- length
is optional
#x
is the length of x
Therefore
$n = 1 # 1 character
last_char = ${x:${#x} - $n}
For future references,
$ man bash
has all the magic
${parameter:offset:length}
Substring Expansion. Expands to up to length characters of parameter starting at the character specified by offset. If length is omitted, expands to the substring of parameter starting at the character specified by offset. length and offset are arithmetic expressions ...