passing variables to awk http://www.theunixschool.com/2011/09/awk-passing-arguments-or-shell.html $ seq 1 2 > seqfile ------------------------------------------------------------------------ I. Through "-v" ------------------------------------------------------------------------ This is by far the easiest approach. Through this method the variable is available in the BEGIN block and END block as well as the main block. The standard awk invocation is one of $ awk -F fs -f program -v var=val file #-v var=val before file $ awk -F fs -v var 'instrutions' file #-v var=val before instructions $ awk -v a=2 'BEGIN{print a^2}' 4 $ awk -v a=2 -v b=3 'BEGIN{print a^b}' #note that each variable needs "-v " 8 $ awk -v a=3 'NR==1{print a^3}' seqfile 27 $ awk -v a=4 'END{print a^4}' seqfile 256 You can also use shell variables as follows: $ hk="hello kitty" $ awk -v a=$hk 'BEGIN{print a}' Hello Kitty Finally, you can set the internal variables for awk also through this method $ awk -v OFS=, '{print $1,$1^2}' seqfile 1,1 1,4 ------------------------------------------------------------------------ II. After command but before file ------------------------------------------------------------------------ In this case the variable q is only available to the main body of the program. It is NOT available in BEGIN. q is set BEFORE acting on the file succeeding it. Thus, you can set a different value of q for each input file. $ awk '{print $1+q}' q=3 seqfile 4 5 $ awk '{print $1+q}' q=3 seqfile q=30 seqfile 4 5 31 #notice that q=30 when the file is switched 32 #Note you can also OFS on the command line $ awk '{print $0,q,$0+q}' q=$x OFS=, seqfile 1,3,4 2,3,5 ------------------------------------------------------------------------ III. Througn "environ" ------------------------------------------------------------------------ $ awk '{print $0+ENVIRON["x"]}' OFS=, infile ------------------------------------------------------------------------ IV. Through painful use of single and double quotes ------------------------------------------------------------------------ $ awk -v OFS=, 'NR==1{print '"$q,$q^3"'}' seqfile 3,27 ======================================================================== an aside (quirk!): To have awk print single or double quotes (Not easy to do this any other way) $ awk -v q="'" '{print q $0 q}' infile $ awk '{print q $0 q}' q='"' infile