0

我不想重命名(或处理)目录(具有特定扩展名)中的文件。文件名可以是任何包含序号的东西,比如

1.aaa.txt
aa 1.txt
aa01bb.txt
78aa1bbb.txt
78aa2bbb.txt

带或不带前导零的编号以及不带前导的新文件名。

所以我有:

NUM=0; for f in *.txt; do NUM=`expr $NUM + 1`; mv "$f" "yyy_$NUM.txt"; done

如何让循环也理解文件顺序,文件编号不带前导零 1,2..10,11..等?

谢谢。

4

1 回答 1

1

下面的 Python 代码应该做排序的东西:

import re
from glob import glob

files = sorted([ file[:-4] for file in glob('*.txt') ])

chunked = []

for i, file in enumerate(files):
    chunks = re.split('(\d+)', file)
    for j, chunk in enumerate(chunks):
        if chunk.isdigit():
            chunks[j] = int(chunk)
    chunked.append((chunks, i))

for chunk, i in sorted(chunked):
    print(files[i])

看起来像这样的目录:

$ ls
01aa.txt  21a.txt  aa01bb.txt   aa10bb.txt
21aa.txt  2aa.txt  aa023bb.txt  aa1bb.txt

它输出:

01aa.txt
2aa.txt
21a.txt
21aa.txt
aa01bb.txt
aa1bb.txt
aa10bb.txt
aa023bb.txt

这与输出简单的sort.

$ ls | sort
01aa.txt
21aa.txt
21a.txt
2aa.txt
aa01bb.txt
aa023bb.txt
aa10bb.txt
aa1bb.txt
于 2013-04-11T12:47:27.227 回答