Bash – Rename Photos to Match Video Titles

bashfilesrename

I have a mostly automated media server and currently have everything going into one folder and being sorted out by file extension into the correct locations.

At the moment the photos are coming in named "folder.jpg" and I need to rename them to match the movie name.

What it looks like now:
Before:

  • /Directory/

    • folder.jpg
    • Movie.mp4
    • Movie.xml

What I need it to look like:
After:

  • /Directory/

    • Movie.jpg
    • Movie.mp4
    • Movie.xml

How would I go about matching the jpg to mp4.

Best Answer

Try:

for movie in ./*/*.mp4; do mv -- "${movie%/*}/folder.jpg" "${movie%.mp4}.jpg"; done

${movie%/*} and ${movie%.mp4} are both examples of suffix removal. ${movie%/*} returns the directory that the movie file is in and ${movie%.mp4} returns the name of the movie file minus the extension .mp4.

Example

Consider three directories, dir1, dir2, and dir3, with the files:

$ ls -1 */*
dir1/Animal Crackers.mp4
dir1/Animal Crackers.xml
dir1/folder.jpg
dir2/folder.jpg
dir2/Monkey Business.mp4
dir2/Monkey Business.xml
dir3/Duck Soup.mp4
dir3/Duck Soup.xml
dir3/folder.jpg

Now, run our command:

$ for movie in ./*/*.mp4; do mv -- "${movie%/*}/folder.jpg" "${movie%.mp4}.jpg"; done

After running our command, the files are:

$ ls -1 */*
dir1/Animal Crackers.jpg
dir1/Animal Crackers.mp4
dir1/Animal Crackers.xml
dir2/Monkey Business.jpg
dir2/Monkey Business.mp4
dir2/Monkey Business.xml
dir3/Duck Soup.jpg
dir3/Duck Soup.mp4
dir3/Duck Soup.xml

Multiple line version

For those who prefer their commands spread over multiple lines:

for movie in ./*/*.mp4
do
    mv -- "${movie%/*}/folder.jpg" "${movie%.mp4}.jpg"
done
Related Question