进行算术运算后,将bash中的前导0添加到整数

时间:2019-02-23 18:19:24

标签: bash

我希望始终有两位数字的输出(例如0394):

i=1; ls | while read l; do mv "$l" name$i; let i=$i+1; done

例如,设置i=01并进行加法运算可能不会返回两位数的输出。

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:3)

通过printf命令,您可以指定数字格式,并使用填充到指定的宽度。正如评论中已经提到的,using ls is unnecessary and even harmful here

i=1
for l in *; do
    printf -v new "name%02i" "$i"
    mv "$l" "$new"
    let i=$i+1
done

答案 1 :(得分:0)

for i in 0{7..9} {10..12}; do echo $i; done

我认为它将为您提供帮助

答案 2 :(得分:0)

我会向您推荐rename,也就是 Perl重命名

rename --dry-run -N "01" '$_=$N' *

示例输出

'file-a' would be renamed to '01'
'file-b' would be renamed to '02'
'file-c' would be renamed to '03'
'file-d' would be renamed to '04'
'file-e' would be renamed to '05'
'file-f' would be renamed to '06'
'file-g' would be renamed to '07'
'file-h' would be renamed to '08'
'file-i' would be renamed to '09'
'file-j' would be renamed to '10'
'file-k' would be renamed to '11'
'file-l' would be renamed to '12'
'file-m' would be renamed to '13'
'file-n' would be renamed to '14'

如果看起来不错,请在没有--dry-run选项的情况下再次运行它以实际重命名文件。

这具有以下好处:

  • 它不会破坏任何新名称会冲突的文件,
  • 您可以使用--dry-run对其进行调用,以检查将要执行的操作无需进行任何操作
  • 您的新名称可能像Perl表达式/程序一样复杂,
  • 如果添加-p开关,它将跨目录重命名并根据需要创建任何中间目录

注意:使用自制软件在MacOS上安装:

brew install rename