1

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

3 Answers 3

3

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).

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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.

1 Comment

No quotes on $1 and you can drop the action entirely as it's the default.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.