linux - 在 Bash 循环中增加一个零填充的 int

标签 linux bash loops unix leading-zero

我正在尝试自动重命名/创建文件,我有一个用于测试的初始脚本,我已经环顾四周但找不到任何相关内容

这是我的示例脚本

#!/bin/bash
file=`hostname`
if [[ -e $file.dx ]] ; then
    i="$(printf "%03d" 1)"
    while [[ -e $name-$i.dx ]] ; do
        let i++
    done
    name=$name-$i
fi
touch $name.dx

脚本在初始文件不存在/不存在时工作正常,但在第 3 次出现后开始出错,如下面的 sh -x

linux@cygwinhost ~/junkyard
$ sh -x exp.sh
++ hostname
+ name=cygwinhost
+ [[ -e cygwinhost.ext ]]
+ touch cygwinhost.ext

linux@cygwinhost ~/junkyard
$ sh -x exp.sh
++ hostname
+ name=cygwinhost
+ [[ -e cygwinhost.ext ]]
++ printf %03d 1
+ i=001
+ [[ -e cygwinhost-001.ext ]]
+ name=cygwinhost-001
+ touch cygwinhost-001.ext

linux@cygwinhost ~/junkyard
$ sh -x exp.sh
++ hostname
+ name=cygwinhost
+ [[ -e cygwinhost.ext ]]
++ printf %03d 1
+ i=001
+ [[ -e cygwinhost-001.ext ]]
+ let i++
+ [[ -e cygwinhost-2.ext ]]
+ name=cygwinhost-2
+ touch cygwinhost-2.ext

linux@cygwinhost ~/junkyard
$

在 001 之后它回落到 -2 没有前导零,非常感谢任何关于我做错的输入
谢谢

最佳答案

您的问题似乎是 001++ 变成了 2 而不是 002。为什么不使用

i=1
printf -v padded_i "%03d" $i
while [[ -e ${name}-${padded_i}.dx ]] ; do
    let i++
    printf -v padded_i "%03d" $i
done

更少的行,但也更困惑:

i=1
while [[ -e ${name}-`printf "%03d" $i`.dx ]] ; do
    let i++
done
name=${name}-`printf "%03d" $i`.dx

更新:使用评论中的printf -v padded_i 建议

关于linux - 在 Bash 循环中增加一个零填充的 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31130107/

相关文章:

linux - 为什么我不能执行这个脚本?

arrays - UIcollectionview 在 Swift 3 中多次重复最后一个单元格

linux - 一系列带有自动关闭 X-windows 的 eog 命令

c++ - 是否有任何库或工具可以计算 Linux 下 C/C++ 中不同进程的 cpu 使用率和其他一些参数?

html - xpath html 将所有列 1 和 2 放在一起并与列 ":"连接

Bash 脚本 - 变量内容作为命令运行

c - 空循环比 C 中的非空循环慢

php - WordPress 以 Posts foreach 循环中的最后一项为目标

linux - shell 和 makefile 之间的公共(public) "include"文件

c++ - 无法使用 Code::Blocks 在 linux mint 中编译 C++