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

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


当前回答

尝试使用loop, let和printf填充:

a=1
for i in *.jpg; do
  new=$(printf "%04d.jpg" "$a") #04 pad to length of 4
  mv -i -- "$i" "$new"
  let a=a+1
done

使用-i标志可以防止自动覆盖现有文件,而使用——可以防止mv将带破折号的文件名解释为选项。

其他回答

将所有文件重命名为序列和小写扩展名:

rename --counter-format 000001 --lower-case --keep-extension --expr='$_ = "$N" if @EXT' *

此处的重命名命令包括-n,用于预览重命名。要实际执行重命名,请删除-n

如果你的重命名不支持-N,你可以这样做:

ls -1 --color=never -c | xargs rename -n 's/.*/our $i; sprintf("%04d.jpg", $i++)/e'

此处的重命名命令包括-n,用于预览重命名。要实际执行重命名,请删除-n

要从给定的数字开始,你可以使用下面的代码(看起来有点难看),只需将123替换为你想要的数字:

ls -1 --color=never  -c | xargs rename -n 's/.*/our $i; if(!$i) { $i=123; } sprintf("%04d.jpg", $i++)/e'

这将按创建时间列出文件(首先列出最新文件,在ls中添加-r以反向排序),然后将此文件列表发送给重命名。Rename使用regex中的perl代码来格式化和增加计数器。

但是,如果您正在处理带有EXIF信息的JPEG图像,我建议您使用exiftool

这来自exiftool文档中的“重命名示例”

   exiftool '-FileName<CreateDate' -d %Y%m%d_%H%M%S%%-c.%%e dir

   Rename all images in "dir" according to the "CreateDate" date and time, adding a copy number with leading '-' if the file already exists ("%-c"), and
   preserving the original file extension (%e).  Note the extra '%' necessary to escape the filename codes (%c and %e) in the date format string.

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

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

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

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

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

#!/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); 
}
find .  | grep 'avi' | nl -nrz -w3 -v1 | while read n f; do mv "$f" "$n.avi"; done

找到。将显示文件夹和子文件夹中的所有文件。

Grep 'avi'将过滤所有avi扩展名的文件。

Nl -nrz -w3 -v1将显示从001 002开始的序列号,后面跟着文件名。

当读n f;做mv "$f" "$ n.v v ";Done会将文件名更改为序列号。