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

fghfilea
fghfileb
fghfilec

我想将它们全部重命名为以前缀jkl开头。是否有一个单独的命令来执行该操作,而不是逐个重命名每个文件?


当前回答

(在我的Mac上)用Ruby做这个要容易得多。下面是两个例子:

# 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

其他回答

这个脚本为我工作递归重命名目录/文件名可能包含空白:

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表达式,它在这个例子中替换了所有;有空间。这当然要根据具体需要进行更换。

在Solaris上,您可以尝试:

for file in `find ./ -name "*TextForRename*"`; do 
    mv -f "$file" "${file/TextForRename/NewText}"
done

这里有一个使用命令行Groovy的方法:

groovy -e 'new File(".").eachFileMatch(~/fgh.*/) {it.renameTo(it.name.replaceFirst("fgh", "jkl"))}'

有很多方法可以做到这一点(并不是所有的方法都适用于所有的unix系统):

ls | cut -c4- | xargs -I§ mv fgh§ jkl§ The § may be replaced by anything you find convenient. You could do this with find -exec too but that behaves subtly different on many systems, so I usually avoid that for f in fgh*; do mv "$f" "${f/fgh/jkl}";done Crude but effective as they say rename 's/^fgh/jkl/' fgh* Real pretty, but rename is not present on BSD, which is the most common unix system afaik. rename fgh jkl fgh* ls | perl -ne 'chomp; next unless -e; $o = $_; s/fgh/jkl/; next if -e; rename $o, $_'; If you insist on using Perl, but there is no rename on your system, you can use this monster.

其中一些有点复杂,列表还远远不够完整,但是您将在这里找到几乎所有unix系统所需的内容。

使用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,它找到了从fghfilea到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——解释你看到的东西是错误的),你可以输入mv——clear重新启动移动文件,或添加更多的例子mv input1 input2,其中input1和input2是其他例子

当你有信心的时候,就打字

mv --filter

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

免责声明:我是这篇论文的合著者。可能很快还会有bash生成功能。