This is a test version of Biostars. For the public version, visit https://www.biostars.org.
How to use a bash variable in awk calculation

I am using the following code to analyze a sequence by seqtk and use the output in awk to print total number of nucleotides and nucleotides marked as N.

seqtk comp "$FILE" | awk '{x+=$2}END{print "Total Nucleotides: " x}' 
seqtk comp "$FILE" | awk '{x+=$9}END{print "Total Unknown Nucleotides: " x}' 
seqtk comp "$FILE" | awk '{x+=$9 ; y+=$2}END{print "Percent of Unknown Nucleotides: " (x/y)*100}'

Since in the above code seqtk calculations are done 3 times, I want to process once and put the result in a variable and reuse. I have tried the following.

RESULT= seqtk comp "$FILE"
echo "$RESULT" | awk '{x+=$2}END{print "Total Nucleotides: " x}' 
echo "$RESULT" | awk '{x+=$9}END{print "Total Unknown Nucleotides: " x}' 
echo "$RESULT" | awk '{x+=$9 ; y+=$2}END{print "Percent of Unknown Nucleotides: " (x/y)*100}'

But the value of x comes out equal to 0.

bash awk

1 answer

use the -v option of awk:

awk -v awk_var=<your bash var>

awk -v x=$RESULT in your specific case

I tried the following

 awk -v x= $RESULT '{x+=$2}END{print "Total Nucleotides: " x}'

It didn't produce any output.

there should be no space behind the x= part

also check if $RESULTS is correctly set (also there should be no space behind the = sign)

The $RESULT variable is empty. Not sure why.

did you remove the space after RESULT= in your cmdline?

moreover, you need to either use the backtick operator: `

or more modern the $() operator. eg RESULT=$(seqtk comp "$FILE")

After adding $() operator now $RESULT is set correctly. However, now I am getting this error: awk: cannot open 11820664 (No such file or directory). I have tried awk -v x=$RESULT '{print "Total Nucleotides: " x[2]}' as well as awk -v x=$RESULT '{x=$2}END{print "Total Nucleotides: " x}'. 11820664 is the third value in the line of data. Thanks

Finally, I made it to work by using the following code: awk '{x=$2}END{print "Total Nucleotides: " x}' <<< "$RESULT"

ok, if the 'value' of RESULTS is something multiline, it's all a bit more tricky.

Log in to answer this question.