我有一个文件夹,其中有不同的文件递增。
kiril_lab_poi08-4-17-001.pdf
kiril_lab_poi08-4-17-002.pdf
kiril_lab_poi08-4-17-003.pdf
kiril_lab_poi08-4-17-004.pdf
kiril_lab_poi08-4-17-005.pdf
kiril_lab_poi08-4-17-006.pdf
kiril_lab_poi08-4-17-007.pdf
kiril_lab_poi08-4-17-009.pdf
kiril_lab_poi08-4-17-010.pdf
kiril_lab_poi08-4-17-011.pdf
kiril_lab_poi08-4-17-012.pdf
[...]
kiril_lab_poi08-4-17-150.pdf
darin_lab_dar04-15-001.pdf
darin_lab_dar04-15-002.pdf
darin_lab_dar04-15-003.pdf
darin_lab_dar04-15-004.pdf
darin_lab_dar04-15-005.pdf
[...]
darin_lab_dar04-15-054.pdf
我的文件从 001 开始,我希望它们从 000 开始:
kiril_lab_poi08-4-17-000.pdf
kiril_lab_poi08-4-17-001.pdf
kiril_lab_poi08-4-17-002.pdf
kiril_lab_poi08-4-17-003.pdf
kiril_lab_poi08-4-17-004.pdf
kiril_lab_poi08-4-17-005.pdf
kiril_lab_poi08-4-17-006.pdf
kiril_lab_poi08-4-17-007.pdf
kiril_lab_poi08-4-17-009.pdf
kiril_lab_poi08-4-17-010.pdf
kiril_lab_poi08-4-17-011.pdf
[...]
kiril_lab_poi08-4-17-149.pdf
darin_lab_dar04-15-000.pdf
darin_lab_dar04-15-001.pdf
darin_lab_dar04-15-002.pdf
darin_lab_dar04-15-003.pdf
darin_lab_dar04-15-004.pdf
[...]
darin_lab_dar04-15-053.pdf
bash中有没有一种方法可以将一堆文件的增量“减”一?
鉴于此文件模式:
$ tree .
.
├── darin_lab_dar04-15-001.pdf
├── darin_lab_dar04-15-002.pdf
├── darin_lab_dar04-15-003.pdf
├── darin_lab_dar04-15-004.pdf
├── darin_lab_dar04-15-005.pdf
├── darin_lab_dar04-15-054.pdf
├── kiril_lab_poi08-4-17-001.pdf
├── kiril_lab_poi08-4-17-002.pdf
├── kiril_lab_poi08-4-17-003.pdf
├── kiril_lab_poi08-4-17-004.pdf
├── kiril_lab_poi08-4-17-005.pdf
├── kiril_lab_poi08-4-17-006.pdf
├── kiril_lab_poi08-4-17-007.pdf
├── kiril_lab_poi08-4-17-009.pdf
├── kiril_lab_poi08-4-17-010.pdf
├── kiril_lab_poi08-4-17-011.pdf
├── kiril_lab_poi08-4-17-012.pdf
└── kiril_lab_poi08-4-17-150.pdf
这是一个 GNU awk 可以做到这一点:
gawk '
match($0, "(^.*[^0-9])([0-9]+)\\.([^.]+)$", a) {
new_file=a[1] sprintf("%0*i", length(a[2]), a[2]-1) "." a[3]
old_file=sprintf("%s%s.%s", a[1],a[2],a[3])
tab=1
while (system("test -e " new_file)==0)
new_file=a[1] a[2] "_" tab++ "." a[3]
printf "\"%s\" => \"%s\"\n", old_file, new_file
s=sprintf("mv \"%s\" \"%s\"", old_file, new_file)
system(s)
}
' <(printf "%s\n" *.pdf)
或者在 Bash 中:
#!/bin/bash
fp='(^.*[^0-9])([0-9]+)\.([^.]+)$'
for fn in *.pdf; do
if [[ $fn =~ $fp ]]; then
old_file=$fn
fp1=${BASH_REMATCH[1]}
fp2=${BASH_REMATCH[2]}
fp3=${BASH_REMATCH[3]}
nn=$(printf "%0*i" ${#fp2} $(( 10#$fp2-1 )) )
tag=0
nf="${fp1}${nn}.${fp3}"
while [ -e "$nf" ]
do
tag+=1
nf="${fp1}${nn}_${tag}.${fp3}"
done
echo "$old_file => $nf"
mv "$old_file" "$nf"
fi
done