Looping through pairs of files with awk

Hi all,

please help me construct the command. i want to loop through all files named bam* and bed*. My awk works for a particular pair but there are too many pairs to do manually.

I have generated multiple files in a folder in a given pattern. The files are named like

bam_fixed1.bam
bed_fixed1.bed
bam_fixed2.bam
bed_fixed2.bed
....
.....

so that every bam file is paired with a bed file. The fixed portion of the filename is the same for a particular pair of bam and bed.

I want to construct an awk command which acts on a bam and its particular bed pair..

what I want to do is for all pairs

awk 'NR == FNR { commands }'  bam_fixed1.bam bed_fixed1.bed > out_fixed1.txt

awk 'NR == FNR { commands }' bam_fixed2.bam bed_fixed2.bed > out_fixed2.txt

...

If there was only 1 file I can use a for loop like

for f in bam_*.bam
do
  commands with $f
done

How do I do this for multiple files and corresponding pairs?

One way to do this:

for f1 in bam_*.bam
do
    mid=${f1#*_}
    mid=${mid%.*}
    f2=bed_${mid}.bed
    awk 'NR==FNR { commands }' $f1 $f2 > out_${mid}.txt
done
1 Like

thanks , this is great !!