我想将目录中的文件重命名为顺序数字。根据文件的创建日期。

例如,sadf.jpg到0001.jpg, wrjr3.jpg到0002.jpg等等,前导零的数量取决于文件的总数(如果不需要,不需要额外的零)。


当前回答

以下是对我有效的方法。 我已经使用重命名命令,这样如果任何文件包含空间的名称,那么mv命令不会混淆空间和实际文件。

Here i replaced spaces , ' ' in a file name with '_' for all jpg files
#! /bin/bash
rename 'y/ /_/' *jpg         #replacing spaces with _
let x=0;
for i in *.jpg;do
    let x=(x+1)
    mv $i $x.jpg
done

其他回答

再次使用Pero的解决方案,只做了很少的修改,因为find将遍历目录树中的项目存储在目录条目中的顺序。在同一台机器上,这将(大部分)在不同的运行中保持一致,如果没有删除,则基本上是“文件/目录创建顺序”。

然而,在某些情况下,您需要获得某种逻辑顺序,例如按名称,这在本例中使用。

find -name '*.jpg' | sort -n | # find jpegs
gawk 'BEGIN{ a=1 }{ printf "mv %s %04d.jpg\n", $0, a++ }' | # build mv command
bash # run that command 

要给一个文件夹中的6000个文件重新编号,您可以使用ACDsee程序的“重命名”选项。

要定义前缀,请使用以下格式:####"*"

然后设置起始号码,按重命名,程序将重命名所有6000个文件的顺序数字。

Pero的回答把我带到了这里:)

我想相对于时间重命名文件,因为图像查看器没有按时间顺序显示图像。

ls -tr *.jpg | # list jpegs relative to time
gawk 'BEGIN{ a=1 }{ printf "mv %s %04d.jpg\n", $0, a++ }' | # build mv command
bash # run that command

我花了3-4个小时来开发这个解决方案: https://www.cloudsavvyit.com/8254/how-to-bulk-rename-files-to-numeric-file-names-in-linux/

if [ ! -r _e -a ! -r _c ]; then echo 'pdf' > _e; echo 1 > _c ;find . -name "*.$(cat _e)" -print0 | xargs -0 -t -I{} bash -c 'mv -n "{}" $(cat _c).$(cat _e);echo $[ $(cat _c) + 1 ] > _c'; rm -f _e _c; fi

这适用于任何类型的文件名(空格,特殊字符),通过find和xargs使用正确的\0转义,如果你喜欢,你可以通过将echo 1增加到任何其他数字来设置开始文件命名偏移量。

在开始时设置扩展名(此处以pdf为例)。它也不会覆盖任何现有文件。

大多数其他解决方案将覆盖已命名为数字的现有文件。如果运行脚本,添加更多文件,然后再次运行脚本,这尤其是个问题。

这个脚本首先重命名现有的数字文件:

#!/usr/bin/perl

use strict;
use warnings;

use File::Temp qw/tempfile/;

my $dir = $ARGV[0]
    or die "Please specify directory as first argument";

opendir(my $dh, $dir) or die "can't opendir $dir: $!";

# First rename any files that are already numeric
while (my @files = grep { /^[0-9]+(\..*)?$/ } readdir($dh))
{
    for my $old (@files) {
        my $ext = $old =~ /(\.[^.]+)$/ ? $1 : '';
        my ($fh, $new) = tempfile(DIR => $dir, SUFFIX => $ext);
        close $fh;
        rename "$dir/$old", $new;
    }
}

rewinddir $dh;
my $i;
while (my $file = readdir($dh))
{
    next if $file =~ /\A\.\.?\z/;
    my $ext = $file =~ /(\.[^.]+)$/ ? $1 : '';
    rename "$dir/$file", sprintf("%s/%04d%s", $dir, ++$i, $ext); 
}