Skip navigation.
Home

Rename files in *nix

In windows renaming a group of files is super easy.. in *nix os's it was less obvious. I finally figured out a decent one-liner..


ls tau/* | sed -e 's/\(.*\)abb\(.*\)/mv & \1aaa\2/' | sh

This will take all files in the tau subdirectory named *abb* and rename them *aaa*. The key is the pipe through sed.. which translated to english says: substitute the replacement string (mv & \1aaa\2) for the first occurrence of the pattern ((.*\)abb\(.*\)). It looks more complicated than it really is thanks to escaping.

ls tau/* | sed -e '(s)ubstitute/pattern/replacement/' | sh (to perform the command)

note: the ampersand symbol is being translated to & on the site.. so the command should use an ampersand wherever the & is currently seen.. I'll fix the drupal module some point. Eye-wink

go on then.

how do you do it in windows?

Matt Fleming's picture

point made

I should have said renaming file extensions in windows is ez..


rename *.aaa *.abb

The double wildcarding doesn't seem to work like I would want it to at all..


touch matt_aaa_matt
rename *aaa* *bbb*
dir matt*
05/26/2006  03:53p                   0 matt_aaa_mattbbb

Yuck..

RE:Rename

On Linux you can use "rename aab aaa *aab*" from util-linux. I don't know about other platforms, but you can simply recompile it. It works fine on my Solaris 9.

Matt Fleming's picture

I looked up the rename

I looked up the rename command on my linux box (Debian 3.1) and got the man page for a perl library..


RENAME(1)              Perl Programmers Reference Guide
NAME
       rename - renames multiple files
SYNOPSIS
       rename [ -v ] [ -n ] [ -f ] perlexpr [ files ]

I was able to achieve what I wanted using


touch matt_aaa_matt
rename 's/aaa/bbb/' *aaa*
ls matt*
matt_bbb_matt

My one-liner should work on a variety of unixes without porting a rename command, but as always there are many ways to get stuff done in *nix like OSs. Smiling

There is one more way to do this

You could use a more algorithmic approach as well:


for i in *abb*; do
  # execute 'mv' with substituted target file name
  mv $i `echo $i | sed -e s/abb/aaa/`;
done