在一个目录中有多个以fgh开头的文件,例如:
fghfilea
fghfileb
fghfilec
我想将它们全部重命名为以前缀jkl开头。是否有一个单独的命令来执行该操作,而不是逐个重命名每个文件?
在一个目录中有多个以fgh开头的文件,例如:
fghfilea
fghfileb
fghfilec
我想将它们全部重命名为以前缀jkl开头。是否有一个单独的命令来执行该操作,而不是逐个重命名每个文件?
当前回答
这为我使用regexp工作:
我想要这样重命名文件:
file0001.txt -> 1.txt
ofile0002.txt -> 2.txt
f_i_l_e0003.txt -> 3.txt
使用[a-z|_]+0*([0-9]+.) regexp,其中([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
警告,小心点。
其他回答
有很多方法可以做到这一点(并不是所有的方法都适用于所有的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也没有。
#!/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
使用mmv:
mmv "fgh*" "jkl#1"
有几种方法,但使用rename可能是最简单的。
使用一个版本的rename (Perl的rename):
rename 's/^fgh/jkl/' fgh*
使用另一个版本的rename(与Judy2K的答案相同):
rename fgh jkl fgh*
您应该检查您的平台的手册页,以确定上述哪一种方法适用。