3

Rookie question. Following this answer Move last part of filename to front, I'm trying to do the same, except all files in my case contains square brackets.

What I want is to move the title to the other side of the brackets (keeping the file extension), so this: title ![s2_e2].mp4 renames to this: [s2_e2]title !.mp4 The first part may contain exclamation marks and spaces, but no other characters which need to be escaped.

I have come up with this, but it only removes the filename until the first square bracket: rename -n 's/^.*\[//' *

Am I on the right path here? And how can I accomplish it with the perl rename tool on Linux?

Thanks!

terdon
  • 242,166

2 Answers2

4

If I understand correctly, you need to move any text inside square brackets to the beginning of the file name. Assuming you only ever have one set of square brackets in the file name, you can do:

rename -n 's/(.*)(\[.+?\])/$2$1/s' *

Running this on your example gives:

$ rename -n 's/(.*)(\[.+?\])/$2$1/s' *
title ![s2_e2].mp4 -> [s2_e2]title !.mp4
terdon
  • 242,166
  • 1
    @they, note that not all variants of perl rename support (or need) that --. A more portable approach would be to use ./*.mp4. Also, in rename you generally want to use the s flag to the substitute command as otherwise . would not match on the newline character. – Stéphane Chazelas Feb 06 '22 at 14:25
  • @StéphaneChazelas Thanks! I'll leave it up to terdon if he wants to correct or roll back my edit. – Kusalananda Feb 06 '22 at 15:08
  • 1
    I'll keep your simplification of the regex, @they, since you're quite right that there's no point in capturing something you don't use (duh), but given that the OP did not ask for something targeting only mp4 files, and Stéphane's point about --, I'll undo the others. – terdon Feb 06 '22 at 16:09
  • Thank you so much! Works like a charm :-) – Nicolas Ø Feb 07 '22 at 07:47
0

I'd use zsh's zmv here:

$ autoload -Uz zmv # best in ~/.zshrc
$ zmv -n '(*)(\[*\])(*)' '$2$1$3'
mv -- 'title ![s2_e2].mp4' '[s2_e2]title !.mp4'

(if there's more than one pair of [/] in the filename, it will move the pair from the right-most [ that has at least one ] following it to the right-most ] after that. So for instance, in [a [b c]] [d [e]], that would move [e]])

There are so many variants of perl's rename these days and so many gotchas with them, that it's hard to keep up with them.

zmv also implements some safeguards of its own. It will check for any conflict before starting doing any renaming.