0

I want to move files based on a specific pattern. I was working with this code, but it does not work well with the task.

for file in *.fastq.gz
do
 dir="${file%R*}"
 mkdir -- "$dir"
 mv -- "$file" "$dir"
done

These are some examples of files:

121123_SN323_A_L002_GPS-100_R1.fastq.gz
121123_SN323_A_L002_GPS-100_R2.fastq.gz
130201_SN132_B_L007_GPS-100_R1.fastq.gz
130201_SN132_B_L007_GPS-100_R2.fastq.gz

121123_SN323_A_L002_GPS-104_R1.fastq.gz
121123_SN323_A_L002_GPS-104_R2.fastq.gz
130201_SN132_B_L007_GPS-104_R1.fastq.gz
130201_SN132_B_L007_GPS-104_R2.fastq.gz

So with these files, I just want to create two folders, GPS100 and GPS104. But I get 4 folders with the code above, namely:

121123_SN323_A_L002_GPS-100_
121123_SN323_A_L002_GPS-104_
130201_SN132_B_L007_GPS-100_
130201_SN132_B_L007_GPS-104_
3

You also need to strip off the front of $dir with dir=GPS${dir#*GPS}.

The resulting script:

$ ls
121123_SN323_A_L002_GPS-100_R1.fastq.gz
121123_SN323_A_L002_GPS-100_R2.fastq.gz
121123_SN323_A_L002_GPS-104_R1.fastq.gz
121123_SN323_A_L002_GPS-104_R2.fastq.gz
130201_SN132_B_L007_GPS-100_R1.fastq.gz
130201_SN132_B_L007_GPS-100_R2.fastq.gz
130201_SN132_B_L007_GPS-104_R1.fastq.gz
130201_SN132_B_L007_GPS-104_R2.fastq.gz

$ for a in *.fastq.gz
do
  dir=${a%_R*}
  dir=GPS${dir#*_GPS}
  mkdir -- "$dir" 2>/dev/null
  mv -i "./$a" "$dir/"
done

$ ls
GPS-100/  GPS-104/

$ ls *
GPS-100:
121123_SN323_A_L002_GPS-100_R1.fastq.gz
121123_SN323_A_L002_GPS-100_R2.fastq.gz
130201_SN132_B_L007_GPS-100_R1.fastq.gz
130201_SN132_B_L007_GPS-100_R2.fastq.gz

GPS-104:
121123_SN323_A_L002_GPS-104_R1.fastq.gz
121123_SN323_A_L002_GPS-104_R2.fastq.gz
130201_SN132_B_L007_GPS-104_R1.fastq.gz
130201_SN132_B_L007_GPS-104_R2.fastq.gz

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.