如何使用增量重命名文件组

How to rename group of files with increment

如何重命名 bash 目录中的一组文件? 例如 : 我有一组文件:

> 0001.txt
> 0002.txt
> 0003.txt
> 0004.txt
...

我需要 0001.txt 变成 0002.txt; 0002.txt 变成 0003.txt 等等。 结果应该是这样的:

0002.txt
0003.txt
0004.txt
0005.txt
...

您可以使用下面的简单脚本:-

#!/bin/bash

while IFS= read -r -d '' file; do

    filename=$(basename "$file")     # Get the absolute path of the file
    filename=${filename%.*}          # Getting file-name without the extension part 'tet0002', 'tet0001'
    filename=${filename:3}           # Getting the numerical part '002', '001'

    # To preserve the leading pad '0's, retaining the decimal representation
    # using printf and appending '10#' notation. '-v' for verbose only (can 
    # be removed)

    mv -v "$file" tet"$(printf %04d "$((10#$filename + 1))")".txt

done < <(find . -maxdepth 1 -mindepth 1 -name "tet*.txt" -type f -print0)

查看实际效果

$ ls tet*
tet0003.txt  tet0005.txt  tet0008.txt

$ ./script.sh
`./tet0005.txt' -> `tet0006.txt'
`./tet0008.txt' -> `tet0009.txt'
`./tet0003.txt' -> `tet0004.txt'

如果您的文件名遵循给定的模式,您可以这样做:

for file in `ls | egrep '^[[:digit:]]+.txt$' | sort -r`
do 
  mv $file `printf %04d $(expr ${file%.*} + 1)`.txt
done

编辑

对于前缀为 tet 的文件名,您可以像这样修改上面的脚本:

for file in `ls | egrep '^tet[[:digit:]]+.txt$' | sort -r`
do 
  filename=${file%.*}
  mv $file tet`printf %04d $(expr ${filename:3} + 1)`.txt
done

出于好奇,如果一些 bash 专家知道避免临时变量的方法,我将不胜感激 filename