Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename multiple files based on pattern in Unix

There are several ways, but using rename will probably be the easiest.

Using one version of rename:

rename 's/^fgh/jkl/' fgh*

Using another version of rename (same as Judy2K's answer):

rename fgh jkl fgh*

You should check your platform's man page to see which of the above applies.


This is how sed and mv can be used together to do rename:

for f in fgh*; do mv "$f" $(echo "$f" | sed 's/^fgh/jkl/g'); done

As per comment below, if the file names have spaces in them, quotes may need to surround the sub-function that returns the name to move the files to:

for f in fgh*; do mv "$f" "$(echo $f | sed 's/^fgh/jkl/g')"; done

rename might not be in every system. so if you don't have it, use the shell this example in bash shell

for f in fgh*; do mv "$f" "${f/fgh/xxx}";done

Using mmv:

mmv "fgh*" "jkl#1"

There are many ways to do it (not all of these will work on all unixy systems):

  • 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.

Some of those are a bit convoluted and the list is far from complete, but you will find what you want here for pretty much all unix systems.