Concatenate multiple files under subdirectories

My directory structure is given below

x:Project_2012-158ASample_4041

SampleSheet.csv
4041_CGTACG_L002_R1_001.fastq
4041_CGTACG_L002_R2_001.fastq
4041_CGTACG_L006_R2_001.fastq
4041_CGTACG_L006_R1_001.fastq

x:Project_2012-158ASample_4027

SampleSheet.csv
4027_TAGCTT_L002_R2_001.fastq
4027_TAGCTT_L006_R1_001.fastq
4027_TAGCTT_L002_R1_001.fastq
4027_TAGCTT_L006_R2_001.fastq

x:Project_2012-158ASample_D425

SampleSheet.csv
D425_ACTGAT_L008_R2_001.fastq
D425_ACTGAT_L008_R1_001.fastq
D425_ACTGAT_L004_R2_001.fastq
D425_ACTGAT_L004_R1_001.fastq

I want to concatenate the files with “R1” and “R2” separately for every sample.
I know

cat file1.fastq file2.fastq > concatenation.fastq 

will give concatenate but how do I do that for all the sudirectories with single script?

Asked By: Jana

||

Like this:

cat ./*/*R2* > result

* – match everything

Be aware that this will get every occurrence of R2 in the filename.

Answered By: week
cd /path/to/Project_2012-158A &&
for dir in Sample*/; do
    for r in R1 R2; do
        outfile=${dir%/}_${r}.fastq
        glob=*_${r}_*.fastq
        cat "$dir"/$glob > "$dir/$outfile" &&
        rm -f "$dir"/$glob
    done
done
Answered By: jw013