I'm attempting to rename a bunch of files with 'rename' and I have my regex nicely setup:

rename --verbose --path 's|^\[(....)\](.*)\.(.*)|$2 ($1).$3|' *

But I'd really like to have each file put into a directory with the common start, so nievely I tried:

rename --verbose --path 's|^\[(....)\](.*)\.(.*)|$2 ($1)/$2 ($1).$3|' *

But that complains that none of the directories exist (as they don't). Am I missing a useful flag for rename or is their a better tool for this?

1 Answer 1


If you're using a Perl-based rename, then there is nothing stopping you from calling mkdir() to create the missing directories:

rename --verbose '
    s|^\[(....)\](.*)\.(.*)|$2 ($1)/$2 ($1).$3| &&
    mkdir("$2 ($1)")' *

This is the same Perl expression that you use, with an added call to mkdir() at the end to create the directory if the expression matches.

Whether the original substitution is correct or not, or whether it makes sense, I don't know (I don't know what types of filenames you have). The point is that since the expression is a generic Perl expression, you're free to use any Perl code, as long as $_ (the default variable) is set to the resulting filename at the end.

  • Thank you. That is both weird and awesome that works. Many uses for this knowledge.
    – LovesTha
    Sep 29, 2020 at 7:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .