How can I rename directories that start with a bracketed year in Bash?

November 13, 2026 3 answers
Asked by Drel.92

I have directories named like [2020] Title and (2021) Title. How can I rename them to 2020 - Title and 2021 - Title in Bash?

Answers

2p~receipt_850

Bash can capture the year and title directly with BASH_REMATCH. Run this from the parent directory:

for dir in */; do name=${dir%/} if [[ $name =~ ^(\[([0-9]{4})\]|\(([0-9]{4})\))\ (.*)$ ]]; then year=${BASH_REMATCH[2]:-${BASH_REMATCH[3]}} title=${BASH_REMATCH[4]} printf 'mv -- %q %q\n' "$name" "$year - $title" fidone

That prints the proposed commands without changing anything. After checking them and making sure the destination names do not already exist, replace the printf line with mv -- "$name" "$year - $title". The quotes keep spaces and other special characters in each name intact.

Haverick.2:

This matches a space after the closing bracket or parenthesis. Names that do not fit the pattern are left alone.

Reply to this answer
!audit~the+teacup

For a manageable batch, vidir from moreutils is another option. It opens a directory listing in an editor, and you can edit the names there before saving. That gives you a chance to check the changes visually without writing a shell loop.

Reply to this answer
Besk.701

I would avoid deleting every bracket, parenthesis, or space with tr. Those characters might also be part of a title, so a broad replacement could change more than the year prefix. Match the prefix specifically and leave the rest of the name alone.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions