bash - 将目录中的最后一个数字加 1?

标签 bash

我想递增作为具有以下结构的字符串传递的目录中的最后一个数字。

将传递的示例字符串是这样的:/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 个特性:

  1. 去除匹配的前缀模式。 ${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.

  2. 删除匹配前缀模式: ${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.

  3. 算术展开

    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/

相关文章:

linux - 运行命令后立即重新启动安全吗?

linux - 获取 adb 日志并将其 grep 到 IF 语句中的字符串

linux - 使用awk处理多个文件

Bash 选项卡完成固定目录中的文件

regex - grep 的管道不适用于尾部?

linux - 用于自动过程的 Cronjob

Linux命令行处理CSV

bash - bash中的 `declare -r`和 `readonly`有什么区别?

c++ - 使用bash脚本进行代码编辑和测试处理

bash - gnuplot for 循环和文件名中的空格