LookIntoEast
LookIntoEast

Reputation: 8808

Errors when passing variable to awk

I'm trying to pass external variable into awk using awk -v but just cannot figure out what's my problem!

for ((c=1;c<=22;c++));do cat hg19.gap.bed|awk -v var={chr"$c"} '{if ("$1"=="$var") print}' > $var.cbs;done

What's the problem of this command? thx

Upvotes: 1

Views: 237

Answers (3)

Tejas Patil
Tejas Patil

Reputation: 6169

I am assuming that chr is just some string and you want to make match with chr1, chr2,....

for ((c=1;c<=22;c++));do cat hg19.gap.bed | awk -v var=chr"$c" '"$1"==var {print}' > chr"$c".cbs;done

Let me know if this works for you.

Upvotes: 0

Jonathan Leffler
Jonathan Leffler

Reputation: 754470

What is the var={chr"$c"} supposed to produce?

What it does produce in this context is {chr1}, {chr2}, ..., {chr22}.

Note that the variable var is an awk variable and not a shell variable. You'd have to redirect to "{chr$c}.cbs" to get the 22 separate files. Within the script, $var will always be $0 since var evaluated as a number is 0.

Rather than running the command 22 times, you can surely do it all in one pass. Assuming that you are using gawk (GNU Awk) or awk on MacOS X (BSD) or any POSIX-compliant awk, you can write:

awk '$1 ~ /\{chr([1-9]|1[0-9]|2[012])\}/ {file=$1".cbs"; print $0 >file;}' hg19.gap.bed

This does the whole job in one pass through the data file.

Upvotes: 1

Kevin
Kevin

Reputation: 56129

In awk, only the field variables start with a $. And you don't want the double quotes within awk. Try if ($1 == var) ....

Using $var actually means the field at the index stored in var, in this case not a valid field (but you can use it to iterate over the fields).

Upvotes: 3

Related Questions