Score:5

Renaming a file using a name of another file in the same folder

in flag

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?

Score:3
in flag

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.
Score:3
jp flag

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.

Vidal avatar
in flag
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).
Raffa avatar
jp flag
@Vidal You are most welcome… It's my pleasure :)
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.