Shell Script – How to Rename Files with Rename Command

renameshell-script

Please advice what is wrong with the following command

find /tmp/dir -name "* *" -type f | rename 's/*/fixed_/g'

remark – I prefer to do that with one command not loop syntax

What I want is to rename all the files under /tmp/dir , by adding the name fixed_ before each file

For example ( the files )

Fevc.txt
Ddve.txt

Should rename to:

fixed_Fevc.txt
fixed_Ddve.txt

Best Answer

Temporary note: there is something wrong - the rename pattern does not handle filenames with path; I'm working on a fix

What is wrong in your command is two things:

find /tmp/dir -name "* *" -type f | rename 's/*/fixed_/g'

  • The -name "* *" matches only file names with a space in it - that's not what you want, right?

    • the solution is to just leave it out; We do not want to exclude files matching some name - we want all.
  • The rename pattern is wrong in two ways

    • you used a shell glob pattern, but it needs to be a regular expression, in short a regex (It can be some general perl expression - let's ignore it and use only s///g)
    • the fixed pattern would match the complete name, and replace it with fixed_. You want to "replace" the "first 0 characters" with fixed_, technically. That's the start of the line, matched with ^. We can leave out the g because there is only one replacement needed per line.

Putting it together, it looks like this:

find /tmp/dir -type f | rename 's/^/fixed_/'

Related Question