Tuesday, November 23, 2010

Passing shell variables to AWK

If you have a shell variable in a bash script you can't pass it to AWK just by putting "$" sign in front of it, but you can enclose them with "'" in AWK code and they will be used in AWK with no problem.

for example you have a bed file called "example.bed":

$ cat example.bed
chr1     1000     2000   id1
chr1     4000     5000   id2
chr1     5500     6000   id3

Let's say you want to concatenate a string (in this case "brain_" string) to column 4 of this file, you can do this in AWK as follows:

$ awk '{OFS="\t";$4="brain_"$4; print;}' example.bed
chr1     1000     2000   brain_id1
chr1     4000     5000   brain_id2
chr1     5500     6000   brain_id3

however if you store the string in a variable as follows in the terminal or in a bash script:

$ TISSUE="brain_"

the following will not work,
$ awk '{OFS="\t";$4=$TISSUE$4; print;}' example.bed

 but this will :

$ awk '{OFS="\t";$4="'"$TISSUE"'"$4; print;}' example.bed
chr1     1000     2000   brain_id1
chr1     4000     5000   brain_id2
chr1     5500     6000   brain_id3

check out for details and other ways to do this at:
http://www.tek-tips.com/faqs.cfm?fid=1281

No comments:

Post a Comment