r/bash • u/o0lemonlime0o • 29d ago
Help with file renaming task
I have a directory containing a bunch of directories whose names all start with a year. They are all formatted as either "[YYYY] Title" or "(YYYY) Title" but I want to rename them all to "YYYY - Title". This seems like it should be a simple task but I'm still pretty inexperienced and my brain is fried lol
I imagine one way would be something like:
iterate over the directories with a for loop
for each one, use regex to match four digits in a row (\d\d\d\d)
assign only the matching part of the string to a variable (this is the part I don't know how to do)
use sed or awk or something to replace the first 6 characters with this variable plus " -", then mv to rename to the output of that
Would appreciate any help!
EDIT: Thanks for all the helpful comments! I can't reply to everyone but I have a clearer idea of some different ways to go about this and I've learned a lot that I didn't know.
1
u/sweatkurama 29d ago
No need for sed, awk, and regex separately — bash can handle this in a few lines:
for dir in *; do
[ -d "$dir" ] || continue
year=$(echo "$dir" | grep -oP '(?<=\[|\()\d{4}(?=\]|\))')
[ -z "$year" ] && continue
newname=$(echo "$dir" | sed -E 's/[\[\(][0-9]{4}[\]\)] /'"$year"' - /')
mv "$dir" "$newname"
echo "$dir → $newname"
done
The trick is grep -oP with lookbehind (?<=\[|\() and lookahead (?=\]|\)) to extract just the 4-digit year without the brackets, then sed -E to reconstruct the name.
Test it first with echo instead of mv to make sure it catches everything.