Home > Back-end >  Replace string in filename with corresponding new name in table
Replace string in filename with corresponding new name in table

Time:07-29

I currently have hundreds of files in a directory named: xxxxxxxxxxxxxxxxMATCH1xxxxxxxxxx.txt , xxxxxxxxxxxxxxxxMATCH2xxxxxxxxxx.txt
and a tab delimited table (codes.txt):

NEWNAME1 MATCH1
NEWNAME2 MATCH2
ect.

Each MATCH is present in five files. For all the files in the directory, I am trying to replace the MATCH in the filename with NEWNAME. The code I have looks like this:

for var in $(cat codes.txt)
    do
        from=$(echo $var | cut -f 2)
        to=$(echo $var | cut -f 1)
        rename $from $to *
    done  

The variables save properly, however the rename command does not rename the files. The rename command works as expected outside the loop. I do not have access to perl rename

CodePudding user response:

One possibility would be to use awk to generate the rename commands based on the contents of your codes file. This output could then be piped to sh and executed. Something like:

awk '{printf "for i in *%s* ; do mv $i ${i/%s/%s} ; done \n", $2, $2, $1}' codes | sh

The generated commands would using bash globbing to locate files by the 'MATCH' strings and would look like:

for i in *MATCH1* ; do mv $i ${i/MATCH1/NEWNAME1} ; done 
for i in *MATCH2* ; do mv $i ${i/MATCH2/NEWNAME2} ; done 

(Note: I am not sure if the awk output piped to sh would be terribly efficient since you are dealing with hundreds of files.)

CodePudding user response:

while read -r new_name match; do
    sed -E "s/(.*)?$match(.*)?/mv & \1$new_name\2/e" <(find . -name '*.txt' -type f)
done < codes.txt

CodePudding user response:

If you can use awk:

awk '{system("rename " $2 " " $1 " *" )}' codes.txt
  • Related