Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I know how I can rename files and such, but I'm having trouble with this.

I only need to rename test-this in a for loop.

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  
like image 279
user3115029 Avatar asked Dec 18 '13 11:12

user3115029


People also ask

How do I partially rename multiple files at once?

Click the Select all button.Quick tip: Alternatively, you can also use the Ctrl + A keyboard shortcut to select all files. You can press and hold the Ctrl key and then click each file to rename. Or you can choose the first file, press and hold the Shift key, and then click the last file to select a group.


2 Answers

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.

like image 102
Tim Zimmermann Avatar answered Sep 20 '22 13:09

Tim Zimmermann


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 
like image 40
dogbane Avatar answered Sep 19 '22 13:09

dogbane