Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi everyone,

I have 100 folders and in each folder i have multiple files as below (Prefix Aardvark change from folder to folder):

Aardvark_GENES_D.fa.1

Aardvark_GENES_D.fa.2

Aardvark_GENES_D.fa.3

Aardvark_GENES_D.fa.4

Aardvark_GENES_D.fa.5

I want to rename them by removing the last extension and replacing GENES with following name the order of name will remain the same for each folder as below:

Aardvark_ACMSD_D.fa

Aardvark_ARID1B_D.fa

Aardvark_CRYM_D.fa

Aardvark_SMO_D.fa

Aardvark_Tlx3_D.fa

I'm using following code it works well for Aardvark bt not for other folder in which prefix contains multiple words e.g for African_savana_elephant it adds Genes name after african jst like below:

African_ACMSD_Savana

African_ARID1B_Savana

African_CRYM_Savana

African_SMO_Savana

where it shoud be like below: African_savana_elephant_ACMSD_D.fa African_savana_elephant_ARID1B_D.fa African_savana_elephant_SMO_D.fa

Code:

paste  <(ls  *.fa.* | sort -t '.' -k3,3n ) list.txt  | awk  '{split($1,a,/_/); printf("mv %s %s_%s_%s\n",$1,a[1],$2,a[3]);}'  | sed 's/\.[0-9]*$//' mv Aardvark_GENES_D.fa.1 Aardvark_ACMSD_D.fa mv Aardvark_GENES_D.fa.2 Aardvark_ARID1B_D.fa mv Aardvark_GENES_D.fa.3 Aardvark_CRYM_D.fa mv Aardvark_GENES_D.fa.4 Aardvark_SMO_D.fa

I'm nwe in perl World Kindly guide me how to edit the above expression for my desired results??????

Replies are listed 'Best First'.
Re: Rename multiple files by removing last extension and editing string
by 1nickt (Canon) on Aug 08, 2017 at 17:54 UTC

    Welcome to the Monastery and to Perl, the One True Religion. You're not apparently using Perl at the moment, as shown in your post. So "edit the above expression" is the wrong approach, here.

    Perl is the right choice for this work, to be sure. A simple script of less than 20 lines will do what you want with error-checking, debug output, and optimizations built in. You should start learning right away! See perlintro, and see the modules Path::Tiny and Path::Iterator for working with files.


    The way forward always starts with a minimal test.