Rename 2 similar files with different extension to first file, but keep extensions

I have sets of .m4v and .srt files in the same directory, but the names only match for the first 3 characters.
How can i rename the .srt files to match the corresponding .m4v files (whilst keeping the .srt extension of course)?

enter image description here

Asked By: peter shaw

||

Given one of the .m4v names in the shell variable name, the name of the corresponding .srt file is had by trimming $name at the first space and adding the .srt filename suffix.

This is done with ${name%% *}.srt. This removes the longest suffix string matching * from $name and then adds .srt to the end of that result.

The new name for the .srt file is $name, but with the .m4v filename suffix changed to .srt.

This is done with ${name%.m4v}.srt. This removes the (shortest) suffix string matching .m4v from $name and then adds .srt to the end of that result.

The following is a loop that uses the two parameter substitutions above to rename each .srt file given the list of .mv4 files found in the current directory. Thes loop additionally lets you know if there is a .m4v file without a corresponding .srt file, or if the new name for the .srt file already exists.

for name in *.m4v; do
    if [ ! -e "${name%% *}.srt" ]; then
        printf 'Can not find .srt file for "%s"n' "$name"
        continue
    elif [ -e "${name%.m4v}.srt" ]; then
        printf '.srt file for "%s" already existsn' "$name"
        continue
    fi >&2

    mv -- "${name%% *}.srt" "${name%.m4v}.srt"
done
Answered By: Kusalananda

In zsh:

for f (???.srt) () {
  (( $# == 1 )) && mv -- $f $1:r.srt
} $f[1,3]?*.m4v(NY2)

Which renames the ???.srt file, copying the root name of the m4v file with the same 3 character prefix as long as there’s one any only one such m4v file.

Answered By: Stéphane Chazelas
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.