在一个目录中有多个以fgh开头的文件,例如:
fghfilea
fghfileb
fghfilec
我想将它们全部重命名为以前缀jkl开头。是否有一个单独的命令来执行该操作,而不是逐个重命名每个文件?
在一个目录中有多个以fgh开头的文件,例如:
fghfilea
fghfileb
fghfilec
我想将它们全部重命名为以前缀jkl开头。是否有一个单独的命令来执行该操作,而不是逐个重命名每个文件?
当前回答
rename fgh jkl fgh*
其他回答
这是如何使用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
使用find, xargs和sed:
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。
我编写了这个脚本来搜索所有.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;
rename fgh jkl fgh*
有很多方法可以做到这一点(并不是所有的方法都适用于所有的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系统所需的内容。