我写了以下几行来获取字符串的最后一个字符:
str=$1
i=$((${#str}-1))
echo ${str:$i:1}
它适用于abcd/
:
$ bash last_ch.sh abcd/
/
它不适用于abcd*
:
$ bash last_ch.sh abcd*
array.sh assign.sh date.sh dict.sh full_path.sh last_ch.sh
它列出当前文件夹中的文件。
最佳答案
根据@perreal,引用变量很重要,但因为在评论中找到解决手头问题的更简单方法之前,我阅读了这篇文章五遍...
str='abcd/'
echo "${str: -1}"
=> /
或者使用评论中指出的 ${str:0-1}
。
str='abcd*'
echo "${str:0-1}"
=> *
注意:${str:-1}
中的多余空格是必须的,否则${str:-1如果
将导致 str
为 null 或空,1
被视为默认值。
${parameter:-word}
Use Default Values. If parameter is unset or null, the
expansion of word is substituted. Otherwise, the value of
parameter is substituted.
感谢所有参与以上事件的人;我在整个线程中适本地添加了 +1!
关于string - 如何在shell中获取字符串的最后一个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17542892/