295

目录中有多个以前缀开头的文件fgh,例如:

fghfilea
fghfileb
fghfilec

我想将它们全部重命名为以 prefix 开头jkl。是否有一个命令可以做到这一点,而不是单独重命名每个文件?

4

23 回答 23

332

有几种方法,但使用rename可能是最简单的。

使用一个版本rename

rename 's/^fgh/jkl/' fgh*

使用另一个版本rename(与Judy2K 的答案相同):

rename fgh jkl fgh*

您应该查看您平台的手册页以了解上述哪一项适用。

于 2009-07-06T11:24:41.700 回答
130

这是如何sed并且mv可以一起使用来进行重命名:

for f in fgh*; do mv "$f" $(echo "$f" | sed 's/^fgh/jkl/g'); done

根据下面的评论,如果文件名中有空格,则可能需要将返回名称的子函数括起来以将文件移动到

for f in fgh*; do mv "$f" "$(echo $f | sed 's/^fgh/jkl/g')"; done
于 2009-07-06T11:38:17.787 回答
90

重命名可能不在每个系统中。因此,如果您没有它,请在 bash shell 中使用此示例的 shell

for f in fgh*; do mv "$f" "${f/fgh/xxx}";done
于 2009-07-07T02:22:44.367 回答
41

使用mmv

mmv "fgh*" "jkl#1"
于 2013-11-21T11:17:37.567 回答
21

有很多方法可以做到这一点(并非所有这些都适用于所有 unixy 系统):

  • ls | cut -c4- | xargs -I§ mv fgh§ jkl§

    § 可以用任何你觉得方便的东西代替。你也可以这样做,find -exec但在许多系统上的行为略有不同,所以我通常避免这样做

  • for f in fgh*; do mv "$f" "${f/fgh/jkl}";done

    正如他们所说,粗鲁但有效

  • rename 's/^fgh/jkl/' fgh*

    真的很漂亮,但是在 BSD 上不存在重命名,这是最常见的 unix 系统 afaik。

  • rename fgh jkl fgh*

  • ls | perl -ne 'chomp; next unless -e; $o = $_; s/fgh/jkl/; next if -e; rename $o, $_';

    如果你坚持使用 Perl,但你的系统上没有重命名,你可以使用这个怪物。

其中一些有点令人费解,并且列表还远未完成,但是您会在这里找到几乎所有 unix 系统所需的内容。

于 2012-10-12T09:41:50.793 回答
16
rename fgh jkl fgh*
于 2009-07-06T11:28:19.977 回答
11

使用find,xargssed:

find . -name "fgh*" -type f -print0 | xargs -0 -I {} sh -c 'mv "{}" "$(dirname "{}")/`echo $(basename "{}") | sed 's/^fgh/jkl/g'`"'

它比@nik 的解决方案更复杂,但它允许递归地重命名文件。比如结构,

.
├── fghdir
│   ├── fdhfilea
│   └── fghfilea
├── fghfile\ e
├── fghfilea
├── fghfileb
├── fghfilec
└── other
    ├── fghfile\ e
    ├── fghfilea
    ├── fghfileb
    └── fghfilec

会变成这样,

.
├── fghdir
│   ├── fdhfilea
│   └── jklfilea
├── jklfile\ e
├── jklfilea
├── jklfileb
├── jklfilec
└── other
    ├── jklfile\ e
    ├── jklfilea
    ├── jklfileb
    └── jklfilec

使其工作的关键xargs从 xargs 调用 shell

于 2014-06-02T22:03:14.770 回答
3

要安装 Perl重命名脚本:

sudo cpan install File::Rename

Stephan202的回答中的评论中提到了两个重命名。基于 Debian 的发行版具有Perl rename。Redhat/rpm 发行版具有C rename
OS X 默认没有安装(至少在 10.8 中),Windows/Cygwin 也没有。

于 2013-05-14T14:02:27.593 回答
3

这是使用命令行 Groovy 的一种方法:

groovy -e 'new File(".").eachFileMatch(~/fgh.*/) {it.renameTo(it.name.replaceFirst("fgh", "jkl"))}'
于 2013-08-06T16:47:37.900 回答
2

在 Solaris 上,您可以尝试:

for file in `find ./ -name "*TextForRename*"`; do 
    mv -f "$file" "${file/TextForRename/NewText}"
done
于 2014-12-23T11:41:05.647 回答
2
#!/bin/sh

#replace all files ended witn .f77 to .f90 in a directory

for filename in *.f77
do 
    #echo $filename
    #b= echo $filename | cut -d. -f1
    #echo $b    
    mv "${filename}" "${filename%.f77}.f90"    
done
于 2014-06-23T09:02:35.120 回答
2

该脚本适用于递归重命名目录/文件名可能包含空格:

find . -type f -name "*\;*" | while read fname; do
    dirname=`dirname "$fname"`
    filename=`basename "$fname"`
    newname=`echo "$filename" | sed -e "s/;/ /g"`
    mv "${dirname}/$filename" "${dirname}/$newname"
done

注意sed在这个例子;中用空格替换所有出现的表达式。这个当然要根据具体需要更换。

于 2019-09-21T16:43:17.840 回答
1

我的重命名批量文件的版本:

for i in *; do
    echo "mv $i $i"
done |
sed -e "s#from_pattern#to_pattern#g” > result1.sh
sh result1.sh
于 2014-08-25T07:01:33.023 回答
1

使用重命名器

$ renamer --find /^fgh/ --replace jkl * --dry-run

--dry-run一旦您对输出看起来正确感到满意,请移除该标志。

于 2013-09-23T17:22:10.240 回答
1

我建议使用我自己的脚本,它可以解决这个问题。它还具有更改文件名编码的选项,并将组合变音符号转换为预先组合的字符,这是我从 Mac 复制文件时经常遇到的问题。

#!/usr/bin/perl

# Copyright (c) 2014 André von Kugland

# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.

$help_msg =
"rename.pl, a script to rename files in batches, using Perl
           expressions to transform their names.
Usage:
    rename.pl [options] FILE1 [FILE2 ...]
Where options can be:
    -v                      Verbose.
    -vv                     Very verbose.
    --apply                 Really apply modifications.
    -e PERLCODE             Execute PERLCODE. (e.g. 's/a/b/g')
    --from-charset=CS       Source charset. (e.g. \"iso-8859-1\")
    --to-charset=CS         Destination charset. (e.g. \"utf-8\")
    --unicode-normalize=NF  Unicode normalization form. (e.g. \"KD\")
    --basename              Modifies only the last element of the path.
";

use Encode;
use Getopt::Long;
use Unicode::Normalize 'normalize';
use File::Basename;
use I18N::Langinfo qw(langinfo CODESET);

Getopt::Long::Configure ("bundling");

# ----------------------------------------------------------------------------------------------- #
#                                           Our variables.                                        #
# ----------------------------------------------------------------------------------------------- #

my $apply = 0;
my $verbose = 0;
my $help = 0;
my $debug = 0;
my $basename = 0;
my $unicode_normalize = "";
my @scripts;
my $from_charset = "";
my $to_charset = "";
my $codeset = "";

# ----------------------------------------------------------------------------------------------- #
#                                        Get cmdline options.                                     #
# ----------------------------------------------------------------------------------------------- #

$result = GetOptions ("apply" => \$apply,
                      "verbose|v+" => \$verbose,
                      "execute|e=s" => \@scripts,
                      "from-charset=s" => \$from_charset,
                      "to-charset=s" => \$to_charset,
                      "unicode-normalize=s" => \$unicode_normalize,
                      "basename" => \$basename,
                      "help|h|?" => \$help,
                      "debug" => \$debug);

# If not going to apply, then be verbose.
if (!$apply && $verbose == 0) {
  $verbose = 1;
}

if ((($#scripts == -1)
  && (($from_charset eq "") || ($to_charset eq ""))
  && $unicode_normalize eq "")
  || ($#ARGV == -1) || ($help)) {
  print $help_msg;
  exit(0);
}

if (($to_charset ne "" && $from_charset eq "")
  ||($from_charset eq "" && $to_charset ne "")
  ||($to_charset eq "" && $from_charset eq "" && $unicode_normalize ne "")) {
  $codeset = langinfo(CODESET);
  $to_charset = $codeset if $from_charset ne "" && $to_charset eq "";
  $from_charset = $codeset if $from_charset eq "" && $to_charset ne "";
}

# ----------------------------------------------------------------------------------------------- #
#         Composes the filter function using the @scripts array and possibly other options.       #
# ----------------------------------------------------------------------------------------------- #

$f = "sub filterfunc() {\n    my \$s = shift;\n";
$f .= "    my \$d = dirname(\$s);\n    my \$s = basename(\$s);\n" if ($basename != 0);
$f .= "    for (\$s) {\n";
$f .= "        $_;\n" foreach (@scripts);   # Get scripts from '-e' opt. #
# Handle charset translation and normalization.
if (($from_charset ne "") && ($to_charset ne "")) {
  if ($unicode_normalize eq "") {
    $f .= "        \$_ = encode(\"$to_charset\", decode(\"$from_charset\", \$_));\n";
  } else {
    $f .= "        \$_ = encode(\"$to_charset\", normalize(\"$unicode_normalize\", decode(\"$from_charset\", \$_)));\n"
  }
} elsif (($from_charset ne "") || ($to_charset ne "")) {
    die "You can't use `from-charset' nor `to-charset' alone";
} elsif ($unicode_normalize ne "") {
  $f .= "        \$_ = encode(\"$codeset\", normalize(\"$unicode_normalize\", decode(\"$codeset\", \$_)));\n"
}
$f .= "    }\n";
$f .= "    \$s = \$d . '/' . \$s;\n" if ($basename != 0);
$f .= "    return \$s;\n}\n";
print "Generated function:\n\n$f" if ($debug);

# ----------------------------------------------------------------------------------------------- #
#                 Evaluates the filter function body, so to define it in our scope.               #
# ----------------------------------------------------------------------------------------------- #

eval $f;

# ----------------------------------------------------------------------------------------------- #
#                  Main loop, which passes names through filters and renames files.               #
# ----------------------------------------------------------------------------------------------- #

foreach (@ARGV) {
  $old_name = $_;
  $new_name = filterfunc($_);

  if ($old_name ne $new_name) {
    if (!$apply or (rename $old_name, $new_name)) {
      print "`$old_name' => `$new_name'\n" if ($verbose);
    } else {
      print "Cannot rename `$old_name' to `$new_name'.\n";
    }
  } else {
    print "`$old_name' unchanged.\n" if ($verbose > 1);
  }
}
于 2013-11-01T11:26:53.713 回答
1

在 Ruby 中执行此操作要容易得多(在我的 Mac 上)。这里有 2 个例子:

# for your fgh example. renames all files from "fgh..." to "jkl..."
files = Dir['fgh*']

files.each do |f|
  f2 = f.gsub('fgh', 'jkl')
  system("mv #{f} #{f2}")
end

# renames all files in directory from "021roman.rb" to "021_roman.rb"
files = Dir['*rb'].select {|f| f =~ /^[0-9]{3}[a-zA-Z]+/}

files.each do |f|
  f1 = f.clone
  f2 = f.insert(3, '_')
  system("mv #{f1} #{f2}")
end
于 2014-05-11T10:04:00.227 回答
1

使用通过示例处理的StringSolver工具(windows 和 Linux bash):

filter fghfilea ok fghreport ok notfghfile notok; mv --all --filter fghfilea jklfilea

它首先根据示例计算一个过滤器,其中输入是文件名和输出(ok 和 notok,任意字符串)。如果 filter 有选项 --auto 或在此命令之后单独调用,它将创建一个文件夹ok和一个文件夹notok并将文件分别推送给它们。

然后使用过滤器,该mv命令是一个半自动移动,它通过修饰符 --auto 变为自动。由于 --filter 使用前面的过滤器,它会找到一个从fghfileato的映射jklfilea,然后将其应用于所有过滤的文件。


其他一站式解决方案

其他等效的执行方式(每行都是等效的),因此您可以选择自己喜欢的执行方式。

filter fghfilea ok fghreport ok notfghfile notok; mv --filter fghfilea jklfilea; mv
filter fghfilea ok fghreport ok notfghfile notok; auto --all --filter fghfilea "mv fghfilea jklfilea"
# Even better, automatically infers the file name
filter fghfilea ok fghreport ok notfghfile notok; auto --all --filter "mv fghfilea jklfilea"

多步解决方案

要仔细查看命令是否运行良好,您可以键入以下内容:

filter fghfilea ok
filter fghfileb ok
filter fghfileb notok

当您确信过滤器是好的时,执行第一步:

mv fghfilea jklfilea

如果要测试并使用之前的过滤器,请键入:

mv --test --filter

如果转换不是您想要的(例如,即使mv --explain您发现有问题),您可以键入mv --clear以重新开始移动文件,或者添加更多示例mv input1 input2,其中 input1 和 input2 是其他示例

当你有信心时,只需输入

mv --filter

瞧!所有重命名都是使用过滤器完成的。

免责声明:我是这项为学术目的而制作的作品的合著者。很快就会有一个 bash 生成功能。

于 2014-01-31T13:51:35.083 回答
1

另一个可能的参数扩展

for f in fgh*; do mv -- "$f" "jkl${f:3}"; done
于 2019-01-13T18:49:02.177 回答
1

通用命令将是

find /path/to/files -name '<search>*' -exec bash -c 'mv $0 ${0/<search>/<replace>}' {} \;

where<search><replace>应该分别替换为您的源和目标。

作为针对您的问题量身定制的更具体示例(应从文件所在的同一文件夹运行),上述命令如下所示:

find . -name 'gfh*' -exec bash -c 'mv $0 ${0/gfh/jkl}' {} \;

对于“试运行”添加echobefore mv,以便您查看生成了哪些命令:

find . -name 'gfh*' -exec bash -c 'echo mv $0 ${0/gfh/jkl}' {} \;

于 2021-01-27T11:21:34.023 回答
0

您也可以使用以下脚本。在终端上运行非常容易......

//一次重命名多个文件

for file in  FILE_NAME*
do
    mv -i "${file}" "${file/FILE_NAME/RENAMED_FILE_NAME}"
done

例子:-

for file in  hello*
do
    mv -i "${file}" "${file/hello/JAISHREE}"
done
于 2017-02-15T12:53:25.723 回答
0

A generic script to run a sed expression on a list of files (combines the sed solution with the rename solution):

#!/bin/sh

e=$1
shift

for f in $*; do
    fNew=$(echo "$f" | sed "$e")
    mv "$f" "$fNew";
done

Invoke by passing the script a sed expression, and then any list of files, just like a version of rename:

script.sh 's/^fgh/jkl/' fgh*
于 2016-10-13T04:25:34.920 回答
0

我编写了这个脚本来搜索所有 .mkv 文件,递归地将找到的文件重命名为 .avi。您可以根据需要对其进行自定义。我添加了一些其他内容,例如从文件路径获取文件目录、扩展名、文件名,以防您将来需要引用某些内容。

find . -type f -name "*.mkv" | while read fp; do 
fd=$(dirname "${fp}");
fn=$(basename "${fp}");
ext="${fn##*.}";
f="${fn%.*}";
new_fp="${fd}/${f}.avi"
mv -v "$fp" "$new_fp" 
done;
于 2016-05-29T16:29:14.723 回答
0

这对我使用正则表达式有用:

我希望文件像这样重命名:

file0001.txt -> 1.txt
ofile0002.txt -> 2.txt 
f_i_l_e0003.txt -> 3.txt

使用 [az|_]+0*([0-9]+. ) 正则表达式,其中 ([0-9]+. ) 是用于重命名命令的组子字符串

ls -1 | awk 'match($0, /[a-z|\_]+0*([0-9]+.*)/, arr) { print   arr[0]  " "  arr[1] }'|xargs  -l mv

生产:

mv file0001.txt 1.txt
mv ofile0002.txt 2.txt
mv f_i_l_e0003.txt 3.txt

另一个例子:

file001abc.txt -> abc1.txt
ofile0002abcd.txt -> abcd2.txt 

ls -1 | awk 'match($0, /[a-z|\_]+0*([0-9]+.*)([a-z]+)/, arr) { print   arr[0]  " "  arr[2] arr[1] }'|xargs  -l mv

生产:

  mv file001abc.txt abc1.txt
  mv ofile0002abcd.txt abcd2.txt 

警告,小心。

于 2016-05-06T19:56:55.020 回答