如何在Bash中将文件名中的填充数字置零?

时间:2020-03-05 18:51:13  来源:igfitidea点击:

使用Bash来重命名以下格式的文件的最佳方法是:

(foo1, foo2, ..., foo1300, ..., fooN)

使用零填充文件名:

(foo00001, foo00002, ..., foo01300, ..., fooN)

解决方案

回答

将执行以下操作:

for i in ((i=1; i<=N; i++)) ; do mv foo$i `printf foo%05d $i` ; done

编辑:更改为使用((i = 1,...)),谢谢mweerden!

回答

这是一个快速解决方案,它假定使用固定长度的前缀(" foo")和固定长度的填充。如果我们需要更多的灵活性,也许这至少是一个有用的起点。

#!/bin/bash

# some test data
files="foo1
foo2
foo100
foo200
foo9999"

for f in $files; do
    prefix=`echo "$f" | cut -c 1-3`        # chars 1-3 = "foo"
    number=`echo "$f" | cut -c 4-`         # chars 4-end = the number
    printf "%s%04d\n" "$prefix" "$number"
done

回答

如果N不是先验固定的:

for f in foo[0-9]*; do mv $f `printf foo%05d ${f#foo}`; done

回答

纯Bash,除了'mv'之外没有其他外部进程:

for file in foo*; do
  newnumber='00000'${file#foo}      # get number, pack with zeros
  newnumber=${newnumber:(-5)}       # the last five characters
  mv $file foo$newnumber            # rename
done

回答

我有一个更复杂的情况,文件名具有后缀和前缀。我还需要对文件名中的数字进行减法。

例如,我希望foo56.png成为foo00000055.png

我希望这对我们进行更复杂的操作有所帮助。

#!/bin/bash

prefix="foo"
postfix=".png"
targetDir="../newframes"
paddingLength=8

for file in ${prefix}[0-9]*${postfix}; do
  # strip the prefix off the file name
  postfile=${file#$prefix}
  # strip the postfix off the file name
  number=${postfile%$postfix}
  # subtract 1 from the resulting number
  i=$((number-1))
  # copy to a new name with padded zeros in a new folder
  cp ${file} "$targetDir"/$(printf $prefix%0${paddingLength}d$postfix $i)
done

回答

它不是纯粹的bash,但是使用rename命令更容易:

rename 's/\d+/sprintf("%05d",$&)/e' foo*