Bash to rename portion of file using match to another

In the portion of bash below I am using rename to match the $id variable to $file and when a match (there will alwsys be one) is found then the $id is removed from each bam and bam.bai in $file and _test is added to thee file name before the extension. Each of the variables is set correctly but rename is not working. Thank you :).

if ! [[ " ${id[*]} " == *\ $file\ * ]]
      then
          for id in $file ; do
           cd "$dir"
           rename s/"IonCode_[0-9][0-9][0-9][0-9]_"/""/g "$id"_test.bam      ## use perl rename to remove barcode and insert $id_test
           rename s/"IonCode_[0-9][0-9][0-9][0-9]_"/""/g "$id"_test.bam.bai  ## use perl rename to remove barcode and insert $id_test
           done
             break
          end
      fi

$id

IonCode_0404 00-0000-xxx-xxx-xxx IonCode_0402 11-1111-yy-yy-yyy

$file

IonCode_0402_xxx.xxx_xxx.bam
IonCode_0402_xxx.xxx_xxx.bam.bai
IonCode_0404_xxx.xxx_xxx.bam
IonCode_0404_xxx.xxx_xxx.bam.bai

desired in $dir

11-1111-yy-yy-yyy_test.bam
11-1111-yy-yy-yyy_test.bam.bai
00-0000-xxx-xxx-xxx_test.bam
00-0000-xxx-xxx-xxx_test.bam.bai

May I ask why you are doing in this in bash with a PERL rename ?

Why not use a normal REGEX in PERL, python or PHP ?

You are using bash with rename because ... ?

1 Like

I do not know python well enough to write a script. php I have not used but have used bash with rename before. There probably is a better way but this was my attempt and I wanted to make a resonable attempt with what I have learned. Thank you :).

I am going to clean this up and reformat and will repost. Thank you :).

Moderator comments were removed during original forum migration.