5

I have a thousand folders containing two files: one of them with a random name (mp4 extension) and the other with a name (srt extension).

I intend to replace the random generated file name by the other file name, keeping extension (mp4, mkv or avi) contained on the same folder. By the way the name of the files use to include () and other foreign characters (ó, ü, etc).

In this situation the script should, in my opinion:

  1. Go into the folder
  2. Get the name with .srt extension
  3. Rename the file with mp4 extension with the new name (keeping whatever the extension)
  4. Get out of the folder
  5. Recursive travel the folders as it may contain other sub-folders

The 5th step may be overridden, though.

I'd appreciate a hand. Can anyone help?

muru
  • 197,895
  • 55
  • 485
  • 740
Vidal
  • 97

2 Answers2

3

Try this little snippet,

shopt -s globstar
for s in **/*.srt; do
    m=( "${s%/*}"/*.mp4 )
    printf '%s --> %s\n' "${m[0]}" "${s%.*}.mp4"
    #mv "${m[0]}" "${s%.*}.mp4"
done
shopt -u globstar
  • Remove the # in front of mv if the output is as expected
  • If there are multiple mp4s in one dir, it will rename only the first it finds. You could easily use loop to mv all mp4's and include a suffix such as _1 etc.
  • If there are multiple srts in one dir, it will rename the mp4 multiple times, so it will be named like the latest srt it finds.
pLumo
  • 26,947
3

Try this from the parent directory where the other sub-directories reside for a dry-run:

find -type f -name "*.srt" |
while IFS= read -r result
    do
    path="${result%/*}"
    fname="${result##*/}"
    name="${fname%.*}"
    for file in "$path"/*.{mkv,mp4,avi}
        do
        [ -e "$file" ] && echo mv -- "$file" "$path/$name.${file##*.}"
        done
    done

When you are satisfied with the output, remove echo to do the actual renaming.

Raffa
  • 32,237
  • 1
    Tested and working. Thanks a lot. I accepted the other solution given 'cos it came earlier. I like your proposal since it is more understandable for a nerd (like me). – Vidal Aug 10 '21 at 17:40
  • @Vidal You are most welcome… It's my pleasure :) – Raffa Aug 11 '21 at 09:25