Search code examples
regexrename

How to use Perl's rename in macOS' terminal to replace random file names with custom string and index?


How do you use Perl's rename to replace the names of all files in a folder with a custom string and an index? I suspect the answer is pretty simple. Still, I haven't been able to piece it together from the manual or the other answers here on SO.

Example

In folder foo I have the files

long complicated name 1.png
random_string_of_letters.png
12312434235512351.png
etc.

The only common denominator is that they have the same extension. I want to rename them

bar1.png
bar2.png
bar3.png
etc.

I'm using Perl's rename (installed via homebrew). The closest I've come is this piece of code from another answer rename -nvs searchword replaceword *. But I am unable to adapt it to do what I wish. I'm used to read * as a wildcard, but it seems to have a different purpose here. I know that you can use regex if you remove -s from the command, and that regex is different from "normal" regex (see a comment to the same answer linked above). But not how to use it.

Edit

When I run brew info rename I get this info:

==> rename: stable 1.601 (bottled), HEAD
Perl-powered file rename script with many helpful built-ins
http://plasmasturm.org/code/rename
/opt/homebrew/Cellar/rename/1.601 (4 files, 44.9KB) *
  Poured from bottle using the formulae.brew.sh API on 2023-08-17 at 11:03:56
From: https://github.com/Homebrew/homebrew-core/blob/HEAD/Formula/r/rename.rb

Solution

  • From the docs, it looks like the following will do:

    rename -Xe '$_ = "bar$N"' *.png
    

    Add a leading -n to do a dry run.

    Optionally add -v for more info.