I have a bunch of videos organized in a directory structure like this: under 'Videos', I have a folder for 'Friends', which contains 'Season 1', 'Season 2', and 'Season 3'. Each season has episodes named 'ep1.mp4', 'ep2.mp4', etc. I'm looking for a way to rename these files according to the format 'Friends_Season_1_ep1.mp4' and move them all to the main 'Videos' directory. What are the best methods to achieve this? Any help would be appreciated!
3 Answers
You can do this with a simple bash script! First, navigate to the directory containing 'Videos'. Then run the following script to move and rename the files:
```bash
cd Videos
# Bash script to rename and move files
shopt -s nullglob
for path in Friends/*/*/*.mp4; do
[[ -f $path ]] || continue
name=${path#*'/'}
name=${name///_}
name=${name// /_}
mv -- "$path" "Videos/${name}"
done
# Remove empty directories
for dir in Friends/*/; do
rmdir "$dir" 2>/dev/null
done
```
This moves every mp4 file to the main 'Videos' directory and renames it based on the folder structure. Just make sure to back up your files before you run any scripts!
If you prefer an interactive approach, you can use the 'vidir' command from the moreutils package. Here's how:
1. Install moreutils if you haven't already.
2. Navigate to the 'Videos' directory.
3. Run `find . -type f | vidir -`.
4. This opens an editor where you can change filenames directly.
It’s a great way to manage files if you like a bit of visual aid while renaming!
If you're looking for a more straightforward way, try the `rename` command if you're on Linux. It's pretty handy for batch renaming files. You can easily rename files using:
```bash
rename 's/Friends/(.*)/(.*)/(Friends_$1_$2)/' Videos/*/*.mp4
```
This uses a Perl regex to rename the files as you want. Just ensure you install it first, as it's part of the util-linux package. It can save you tons of time when renaming files!
Thanks, I’ll look into the rename command! Is it installed by default on most systems?

Thanks for sharing this! Just to clarify, does this script retain the original folder also? I want to keep things clean.