How can I recursively rename audiobook tracks based on their parent directories?
Asked by
CuriousCheetah42
I'm trying to organize my ripped audiobooks, which are currently in a directory structure that includes multiple discs. Each disc contains several tracks, and I need to rename the tracks so that their filenames reflect their disc, in a uniform way. For example, I want to change:
/book/
disc 1/
track 1.mp3, track 2.mp3
disc 2/
track 1.mp3, track 2.mp3
Into a single directory with names like:
/book/
disc 01 - track 1.mp3, disc 01 - track 2.mp3, disc 02 - track 1.mp3, disc 02 - track 2.mp3
I know I can use the 'mv' command in a loop for part of it, but I need help making it recursive and ensuring the filenames are generated based on their respective parent folders.
Answers
Here's a simple script you can use that recursively renames your tracks based on their parent directory names:
```bash
find /book -name '*.mp3' | while read -r track; do
cp "${track}" "/book/$(basename "$(dirname "$track")") - $(basename "${track}")"
done
```
This will find all `.mp3` files under the `/book` directory, then copy them with the correct naming format. Just swap `cp` with `mv` if you want to move instead of copying.
Reply to this answer
I found a tool called genFRN on GitHub. Itโs designed to rename files based on their parent directories, but just keep in mind it processes one directory at a time. You can search online for ways to run scripts recursively for multiple subdirectories.
Reply to this answer
Here's a more robust approach using a script with Perl:
```bash
$ find . -name *.mp3 ! -type l -exec ./myrename {} ;
```
This will rename your files correctly using their parent directory names while ensuring everything is handled properly.
Reply to this answer
Just to clarify, you want the format to be like this:
/book/
disc 01 - track 1.mp3
disc 01 - track 2.mp3
disc 02 - track 1.mp3
disc 02 - track 2.mp3
Right?
Reply to this answer
Add your answer
Answers are reviewed before publication.
TechSavvyNerd: I tried this and ran into an error: "cp: cannot create regular file '/book/disc 1 - track 1.mp3': No such file or directory." Any idea what might be wrong?
ScriptGuru: You may need to check if the destination directory exists before copying. Consider creating it if not, or ensure there aren't any spaces in your directory names that might need to be escaped.