3

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.

7

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
  • 1
    +1 nice one. One minor question: is there any reason to use ./*/*.mp4 instead of simply*/*.mp4 without the leading dot? – Sparhawk May 26 at 12:38
  • Not sure why it wasn't working for me with the single line. Changed to multi-line version and it works great! Thank you. – RobertW May 26 at 12:45
  • 1
    @Sparhawk With */*.mp4, there is the possibility that the path will start with a dash, -, which could cause mv or another such program to treat the path as an option leading to surprising and bad results. Consequently, it is a good habit to start paths with ./ so that the path will never be misinterpreted as an option. (Here, out of habit, I also used mv -- so consider the two together as a belt-and-suspenders approach.) – John1024 May 26 at 13:00
  • @RobertW That's curious: I used the single-line version for testing. Anyway, glad one of the versions works for you. – John1024 May 26 at 13:02
  • 1
    Thank you for the explanation @John1024. And excellent analogy! – Sparhawk May 26 at 13:02
0
find . -type f -name "*.mp4" -execdir bash -c ' [[ -f folder.jpg ]] && mv -v folder.jpg "$(basename {} .mp4).jpg"' \;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.