bash 如何在bash中检查字符串中的最后一个字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19271959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 08:14:58  来源:igfitidea点击:

How can I check the last character in a string in bash?

regexbashshellcommand-line

提问by Mild Fuzz

I need to ensure that the last character in a string is a /

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

x="test.com/"

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

at the moment, false always fires.

目前, false 总是会触发。

回答by fedorqui 'SO stop harming'

Like this, for example:

像这样,例如:

$ 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

回答by devnull

Your condition was slightlyincorrect. When using =~, the rhs is considered a pattern, so you'd say patternand not /pattern/.

你的情况有点不正确。使用时=~,rhs 被视为一种模式,因此您会说pattern而不是/pattern/

You'd have got expected results if you said

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

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

instead of

代替

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

回答by devnull

You can index strings in Bash using ${var:index}and ${#var}to get the length of the string. Negative indices means the moving from the end to the start of the string so that -1is index of the last character:

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

if [[ "${x:${#x}-1}" == "/" ]]; then
    # last character of x is /
fi

回答by crafter

You can do this generically using bash substrings $(string:offset:length}- lengthis optional

您可以使用 bash 子字符串一般地执行此操作$(string:offset:length}-length是可选的

#xis the length of x

#x是 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 ...

${参数:偏移:长度}

子串扩展。从 offset 指定的字符开始,最多扩展到参数的 length 个字符。如果省略length,则扩展到从offset 指定的字符开始的参数的子字符串。长度和偏移量是算术表达式...