1

I have a shell script which does couple of things like storing values in a variable. As an example here is my script:

for i in ../../*.bam
do
        fn=$(basename $i)
        fn=${fn%_Aligned.sortedByCoord.out.bam}

        bamToBed -i $i | awk -v OFS="\t" '{if($6 ~ /+/){print $1,$2+67,$2+67+1,$4,$5,$6}else{print $1,$3-67-1,$3-67,$4,$5,$6}}' | awk -v OFS="\t" '$3 > 0' > ${fn}_pos.bed

        sortBed -g $genome -i ${fn}_pos.bed > ${fn}_n_pos.bed

        mv ${fn}_n_pos.bed ${fn}_pos.bed

        perl counter.pl ${fn}_pos.bed | sortBed -g $genome -i stdin | intersectBed -g $genome -sorted -a <(cat $genome | awk -v OFS="\t" '{print $1,"0",$2}') -b stdin -wa -wb | cut -f 4-7 > ${fn}.bedGraph

        bedGraphToBigWig ${fn}.bedGraph $genome ${fn}.bw

        a=`samtools view $i | wc -l`

        intersectBed -g $genome -sorted -c -a <(cat test.bed | awk -v OFS="\t" '{print $1,$2-50,$2+400,$4,$5,$6}') -b ${fn}_pos.bed | cut -f 4,7 | awk -v OFS="\t" '{print $1,$2,$a}'> ${fn}_IP_count.txt

        cat ${fn}_IP_count.txt | awk -v OFS="\t" '{print $1,$2,$a}' > final.txt
done

As you can see this line in the code where I have declared a variable a. This stores a number. Then I created a 2 column text file, tab delimited ${fn}_IP_count.txt I want to add a third column in this file where the third column is the value stored in the variable a to every line. As an example,2 column file looks like this:

gene1   200
gene2   23
gene3   45
gene4   10

Let's say the value stored in the variable a is 245676, then I want the output to be stored in the third column like this

gene1   200 245676
gene2   23  245676
gene3   45  245676
gene4   10  245676

I tried it using awk but I am not getting the right answer. Any help would be appreciated.

4

You pass other variables in the same way as you are passing OFS, using -v

Ex.

awk -v OFS="\t" -v a="$a" '{print $1,$2,a}'
  • works pretty neatly. I tried this and this worked too awk -v OFS="\t" '{print $1,$2,"'$a'"}' – user3138373 Sep 11 at 16:10
  • 1
    @user3138373 Note that the code that you propose contains a code injection vulnerability. Take for example a='"; print "hi" >"newfile'. Running your code would create the file newfile with the string hi in it. – Kusalananda Sep 11 at 16:47

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.