Rename multiple files, but only rename part of the filename in Bash

If you have all of these files in one folder and you're on Linux you can use:

rename 's/test-this/REPLACESTRING/g' *

The result will be:

REPLACESTRING.ext
REPLACESTRING.volume001+02.ext
REPLACESTRING.volume002+04.ext
...

rename can take a command as the first argument. The command here consists of four parts:

  1. s: flag to substitute a string with another string,
  2. test-this: the string you want to replace,
  3. REPLACESTRING: the string you want to replace the search string with, and
  4. g: a flag indicating that all matches of the search string shall be replaced, i.e. if the filename is test-this-abc-test-this.ext the result will be REPLACESTRING-abc-REPLACESTRING.ext.

Refer to man sed for a detailed description of the flags.


Use rename as shown below:

rename test-this foo test-this*

This will replace test-this with foo in the file names.

If you don't have rename use a for loop as shown below:

for i in test-this*
do
    mv "$i" "${i/test-this/foo}"
done

Function

I'm on OSX and my bash doesn't come with rename as a built-in function. I create a function in my .bash_profile that takes the first argument, which is a pattern in the file that should only match once, and doesn't care what comes after it, and replaces with the text of argument 2.

rename() {
    for i in $1*
    do
        mv "$i" "${i/$1/$2}"
    done
}

Input Files

test-this.ext
test-this.volume001+02.ext
test-this.volume002+04.ext 
test-this.volume003+08.ext 
test-this.volume004+16.ext 
test-this.volume005+32.ext 
test-this.volume006+64.ext 
test-this.volume007+78.ext 

Command

rename test-this hello-there

Output

hello-there.ext
hello-there.volume001+02.ext
hello-there.volume002+04.ext 
hello-there.volume003+08.ext 
hello-there.volume004+16.ext 
hello-there.volume005+32.ext 
hello-there.volume006+64.ext 
hello-there.volume007+78.ext