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

Viewed 98595

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 
6 Answers

Without using rename:

find -name test-this\*.ext | sed 'p;s/test-this/replace-that/' | xargs -d '\n' -n 2 mv

The way it works is as follows:

  1. find will, well, find all files matching your criteria. If you pass -name a glob expression, don't forget to escape the *.

  2. Pipe the newline-separated* list of filenames into sed, which will:

    a. Print (p) one line.

    b. Substitute (s///) test-this with replace-that and print the result.

    c. Move on to the next line.

  3. Pipe the newline-separated list of alternating old and new filenames to xargs, which will:

    a. Treat newlines as delimiters (-d '\n').

    b. Call mv repeatedly with up to 2 (-n 2) arguments each time.

For a dry run, try the following:

find -name test-this\*.ext | sed 'p;s/test-this/replace-that/' | xargs -d '\n' -n 2 echo mv

*: Keep in mind it won't work if your filenames include newlines.

to rename index.htm to index.html

rename [what you want to rename] [what you want it to be] [match on these files]
rename .htm .HTML *.htm

renames index.htm to index.html It will do this for all files that match *.htm in the folder.

thx for your passion and answers. I also find a solution for me to rename multiple files on my linux terminal and directly add a little counter. With this I have a very good chance to have better SEO names.

Here is the command

count=1 ; zmv '(*).jpg' 'new-seo-name--$((count++)).jpg'

I also do a live coding video and publush it to YouTube

Related