bash - unix awk column equal to a variable -


i want print lines 2 columns equal variable, example, input:

2607s1  nc_000067.6 95.92   49  1   1   3   50  1e-14   84.2 2607s1  nc_000067.6 97.73   44  1   0   7   50  4e-14   84.2 2607s1  nc_000067.6 97.67   43  1   0   8   50  1e-13   75.0 

and variables first , last column:

a="2607s1"; b="84.2" 

and using awk command, output:

2607s1  nc_000067.6 95.92   49  1   1   3   50  1e-14   84.2 2607s1  nc_000067.6 97.73   44  1   0   7   50  4e-14   84.2 

i have tried following not work:

awk -v '$1==$a' && '$10==$b' test_file cat test_file|awk '$1=="($a)" && $10=="($b)"' cat test_file|awk '$1==($a) && $10==($b)' cat test_file|awk '$1=="$a" && $10=="$b"' 

moreover, running in while loop, $a , $b keep changing please help..

you passing shell variables awk command using wrong method. should like

awk -v a="$a" -v b="$b" '$1==a && $10 == b'  

what does

  • -v a="$a" creates awk variable a , assigns value of shell variable $a it.

  • -v b="$b" creates awk variable b.

or

awk '$1==a && $10 == b' a="$a" b="$b" file 

when write statement this

awk -v '$1==$a' && '$10==$b' test_file 

awk doesn't know $a $b because both shell variables.

and correct method of using -v passing shell variables in demonstrated in examples.

from awk manuals

-v var=val     --assign var=val      assign   value  val variable var, before execution of     program begins.  such variable values available       begin block of awk program. 


test

$ cat file  2607s1  nc_000067.6 95.92   49  1   1   3   50  1e-14   84.2 2607s1  nc_000067.6 97.73   44  1   0   7   50  4e-14   84.2 2607s1  nc_000067.6 97.67   43  1   0   8   50  1e-13   75.0  $ a="2607s1"; b="84.2"  $ awk -v a="$a" -v b="$b" '$1==a && $10 == b' file  2607s1  nc_000067.6 95.92   49  1   1   3   50  1e-14   84.2 2607s1  nc_000067.6 97.73   44  1   0   7   50  4e-14   84.2 

Comments