Monday, May 11, 2015

Combine two variables in the same order in bash

If you want to combine two for loops in bash, you will get all possible combinations, e.g.

A="0 1 2 3"
B="ab CD ef GH"
for i in $A ; do
    for j in $B ; do
       echo $i$j
    done
done


0ab
0CD
0ef
0GH
1ab
1CD
1ef
1GH
2ab
2CD
2ef
2GH
3ab
3CD
3ef
3GH



If you want to combine variables of the same order use the following code:

A=(0 1 2 3); B=(ab CD ef GH)
for i in $(seq 0 8)
do
echo ${A[$i]}${B[$i]}
done


0ab
1CD
2ef
3GH


For example if you have files that you have to merge you can use this loop.n this example we merge 4 fastq files for 9 samples with different names.


A=(1 2 3 4 5 6 7 14 15); B=("90715018_S1" "317155-2" "7103002-3" "1042702-4" "313605-4" "24635-2" "2040401" "24156" "1483"); for i in $(seq 0 9);
do
cat ${B[$i]}_S${A[$i]}_L001_R1_001.fastq.gz ${B[$i]}_S${A[$i]}_L002_R1_001.fastq.gz ${B[$i]}_S${A[$i]}_L003_R1_001.fastq.gz ${B[$i]}_S${A[$i]}_L004_R1_001.fastq.gz >  ${B[$i]}_S${A[$i]}_L001_L004_R1_001$.fastq.gz


cat ${B[$i]}_S${A[$i]}_L001_R2_001.fastq.gz ${B[$i]}_S${A[$i]}_L002_R2_001.fastq.gz ${B[$i]}_S${A[$i]}_L003_R2_001.fastq.gz ${B[$i]}_S${A[$i]}_L004_R2_001.fastq.gz >  ${B[$i]}_S${A[$i]}_L001_L004_R2_001$.fastq.gz


done

No comments:

Post a Comment