Ubuntu – rename multiple files with delimiters

awkcommand linerenamesed

How could I rename multiple files like,

IonXpress_049.T11014.R_2014_11_13_11_26_35_user_PR2-41-Pooling0026_3140_13112014.bam
IonXpress_050.T11114.R_2014_11_13_11_26_35_user_PR2-41-Pooling0026_3140_13112014.bam

To,

T11014.bam 
T11114.bam

Best Answer

There are several ways to rename from command line. Here is a one liner. Go to the directory where the .bam files are located and try this,

for i in *.bam; do mv "$i" "$(echo $i | awk -F"." '{print $2}').bam"; done

How it works:

  • Using a for loop and shell glob trapping the desired files,
    for i in *.bam
    do
        mv source destination
    done
  • Next extract the part that you want to keep i.e. the second field of the string separated by . using awk as,
    $ echo IonXpress_049.T11014.R_2014_11_13_11_26_35_user_PR2-41-Pooling0026_3140_13112014.bam | awk -F"." '{print $2}'
    $ T11014

One can use custom field separator using -F option. See man awk for more.

Related Question