我想递增作为具有以下结构的字符串传递的目录中的最后一个数字。
将传递的示例字符串是这样的:/efs/etc/alex15_0
函数完成后会变成/efs/etc/alex15_1
我想递增的数字总是在 _
符号之后,它只出现一次,我想它可以用作索引。它将递增 1,没有小数,只是常规整数。
我尝试使用
获取最后一个字符${str:$i:1}
但这显然不适用于像 99 这样会变成 910 的情况
在 Java 中,我会获取 '_' 的索引,然后从该索引中获取长度的子字符串并递增它。
str=/efs/etc/alex15_0
updateVer()
{
}
最佳答案
以下应该可以解决问题:
$ str=/efs/etc/alex15_0
$ echo ${str%_*}_$((${str##*_}+1))
/efs/etc/alex15_1
它的工作方式是使用 bash 的 3 个特性:
去除匹配的前缀模式。
${pattern%word}
这用于去除最后的数字并保留字符串的头部。The word is expanded to produce a pattern just as in pathname expansion. If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the
%
case) or the longest matching pattern (the%%
case) deleted.删除匹配前缀模式:
${parameter##word}
这用于在字符之后给出最终数字。 p> The word is expanded to produce a pattern just as in pathname expansion. If the pattern matches the beginning of the value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the
#
case) or the longest matching pattern (the##
case) deleted.算术展开
Arithmetic expansion allows the evaluation of an arithmetic expression and the substitution of the result. The format for arithmetic expansion is:
$((expression))
关于bash - 将目录中的最后一个数字加 1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55747145/