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

fghfilea
fghfileb
fghfilec

我想将它们全部重命名为以前缀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系统所需的内容。

其他回答

安装Perl重命名脚本:

sudo cpan install File::Rename

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

并不是每个系统都需要重命名。如果没有,就用壳层 本例使用bash shell

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

在文件列表上运行sed表达式的通用脚本(将sed解决方案与重命名解决方案结合在一起):

#!/bin/sh

e=$1
shift

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

通过向脚本传递一个sed表达式来调用,然后是任何文件列表,就像rename的一个版本:

script.sh 's/^fgh/jkl/' fgh*

使用mmv:

mmv "fgh*" "jkl#1"

我编写了这个脚本来搜索所有.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;