6

我需要确保字符串中的最后一个字符是/

x="test.com/"

if [[ $x =~ //$/ ]] ; then
        x=$x"extention"
else
        x=$x"/extention"
fi

目前, false 总是触发。

4

4 回答 4

12

像这样,例如:

$ 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
于 2013-10-09T12:26:50.070 回答
3

${var:index}您可以在 Bash 中使用和来索引字符串${#var}以获取字符串的长度。负索引意味着从字符串的末尾移动到字符串的开头,因此这-1是最后一个字符的索引:

if [[ "${x:${#x}-1}" == "/" ]]; then
    # last character of x is /
fi
于 2013-10-09T12:38:17.107 回答
3

你的情况有点不正确。使用=~时,rhs 被认为是一种模式,所以你会说patternand not /pattern/

如果你说,你会得到预期的结果

if [[ $x =~ /$ ]] ; then

代替

if [[ $x =~ //$/ ]] ; then
于 2013-10-09T12:32:58.233 回答
0

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 ...

于 2013-10-09T12:44:06.703 回答