[英]one liner in bash (using perl or awk) to change extension of multiple files?
What's the easiest way in the bash shell to rename a bunch of files? 在bash shell中重命名一堆文件的最简单方法是什么? To rename each *.ext
file in the current directory to *.otherext
? 要将当前目录中的每个*.ext
文件重命名为*.otherext
? I'm open to solutions that use perl or awk, doesn't have to be pure bash. 我对使用perl或awk的解决方案持开放态度,而不必是纯粹的bash。 Any ideas? 有任何想法吗?
To be clear it would mean: 要清楚,这意味着:
mv a.ext a.otherext
mv b.ext b.otherext
...
etc. for all *.ext
There are a few ways to do this. 有几种方法可以做到这一点。 There's a rename
program written in Perl: 有一个用Perl编写的rename
程序:
rename 's/\.ext\z/.otherext/' *.ext
But there's also another (incompatible) rename
program around, for which you'd have to do this: 但是,还有另一个(不兼容的) rename
程序,您必须为此执行以下操作:
rename .ext .otherext *.ext
There's also a program called mmv
: 还有一个名为mmv
的程序:
mmv '*.ext' '#1.otherext'
Using plain bash: 使用普通bash:
for i in *.ext; do mv -- "$i" "${i%.ext}.otherext"; done
Using plain perl: 使用纯Perl:
perl -we 'for my $old (glob "*.ext") { (my $new = $old) =~ s/\.ext\z/.otherext/; rename $old, $new or warn "$old -> $new: $!\n"; }'
Since you asked for what a Python version might look like, I thought I would add it for posterity. 由于您询问的是Python版本的外观,因此我想为后代添加它。
#!/usr/bin/python
from glob import glob
from os import rename
for f in glob("*.ext"):
rename(f, f[:-3] + "otherext")
The one line version (not as nice looking): 单行版本(外观不太好):
python -c "import glob,os;[os.rename(f, f[:-3] + \"otherext\") for f in glob.glob(\"*.ext\")]"
A python one-liner: python单一代码:
python -c "import shutil, glob; [shutil.move(i,i.replace('.txt','.ext')) for i in glob.glob('*.txt')]"
Take advantage of ' and " instead of escape characters and the replace function 利用'和'代替转义字符和替换功能
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.