简体   繁体   中英

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? To rename each *.ext file in the current directory to *.otherext ? I'm open to solutions that use perl or awk, doesn't have to be pure 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:

rename 's/\.ext\z/.otherext/' *.ext

But there's also another (incompatible) rename program around, for which you'd have to do this:

rename .ext .otherext *.ext

There's also a program called mmv :

mmv '*.ext' '#1.otherext'

Using plain bash:

for i in *.ext; do mv -- "$i" "${i%.ext}.otherext"; done

Using plain 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.

#!/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 -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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM