Search code examples
bashshellawkcatbatch-rename

Batch Rename a file based of part of name of second file


I want to batch rename some file based of Part of Name of other files
let me explain my question with a example, I think its better in this way
I have some file with these name in a folder

sc_gen_08-bigfile4-0-data.txt
signal_1_1-bigfile8.1-0-data.txt

and these file in other folder

sc_gen_08-acaaf2d4180b743b7b642e8c875a9765-1-data.txt
signal_1_1-dacaaf280b743b7b642e8c875a9765-4-data.txt

I want to batch rename first files to name of second files, how can I do this? also file in both first and second folder have common in name

name(common in file in both folder)-[only this part is diffrent in each file]-data.txt

Thanks (sorry if its not a good question for everyone, but its a question for me)


Solution

  • Let's name the original folder as "folder1" and the other folder as "folder2". Then would you please try the following:

    #!/bin/bash
    
    folder1="folder1"                       # the original folder name
    folder2="folder2"                       # the other folder name
    
    declare -A map                          # create an associative array
    for f in "$folder2"/*-data.txt; do      # find files in the "other folder"
        f=${f##*/}                          # remove directory name
        common=${f%%-*}                     # extract the common substring
        map[$common]=$f                     # associate common name with full filename
    done
    
    for f in "$folder1"/*-data.txt; do      # find files in the original folder
        f=${f##*/}                          # remove directory name
        common=${f%%-*}                     # extract the common substring
        mv -- "$folder1/$f" "$folder1/${map[$common]}"
                                            # rename the file based on the value in map
    done